Convert date to SQL datetime - sql

I'm somewhat new to T-SQL and despite reading a number of articles that indicate this should work, I'm having trouble converting October 1st of the current year to a datetime.
I've tried:
SELECT CAST(DATEPART(year, GETDATE()) + '1015' AS DATETIME)
SELECT CONVERT(datetime, 'Oct 15 ' + DATEPART(YEAR,GETDATE()),100)
And all kinds of variations.
Any ideas? I need to set a datetime variable to whatever Oct 1st of the current year is.

What you're trying to is close, but DATEPART returns a number, so the "+" is doing addition, not concatenation.
Try it like this:
SELECT CAST(CAST(DATEPART(year, GETDATE()) AS VARCHAR(4)) + '1015' AS DATETIME)
edit -- Ed beat me to it, and the Concat function is better too.
But if you really wanted to knock it out of the park, try this...
SELECT DATEADD(month, 9, DATEADD(year, DATEDIFF(year, 0, getdate()), 0)) As October1CurrentYear
No casting required!

Your first query is very close. The problem is that the plus sign (+) for concatenation is actually giving you a numeric value, which you can't cast to a date.
To concatenate a year and '1015' and end up with a string, use the CONCAT function instead:
SELECT CAST(CONCAT(DATEPART(YEAR, GETDATE()), '1015') AS DATE)

Related

How to subtract one month from a date using SQL Server

I have a date in format dd/mm/yyyy. I want to subtract one month from it.
I am using this code but the output is "09/10/2020" I don't know why my code does the subtraction of the year -2 also.
This is my request
SELECT
FORMAT(CONVERT (DATE, DATEADD(MONTH, -1, CONVERT(char(9), GETDATE()))), 'dd/MM/yyyy')
you need to change it to:
select format(CONVERT (date,DATEADD(MONTH, -1,GETDATE())), 'dd/MM/yyyy' )
but as Larnu stated. it seems like you need to change the column.
Your current code doesn't work as expected because:
SELECT CONVERT(char(9), GETDATE());
Returns this (at least in my language):
Nov 9 20
Which is, unfortunately, and again in my language, a valid date (but in {20}20, not {20}22).
Even in the right style (103), char(9) would yield 10/11/202 tomorrow, since 9 digits is only enough if either the day or month is a single digit.
Don't know why you are converting GETDATE() to a string. Just perform date math on it and then format it if you need to (using a specific style number, e.g. 103 for d/m/y):
SELECT CONVERT(char(10), DATEADD(MONTH, -1, GETDATE()), 103);
I really wouldn't use FORMAT() for such simple output, as the CLR overhead really isn't worth it. Ideally you leave it as a date/time type until presentation time - surely your presentation layer can present your date as d/m/y if that's really a wise idea.
And if you are storing or passing dates as strings (and worse, in regional formats like d/m/y) you really should consider fixing that.
First of all,
You should be storing your Date as a string for easier manipulation. If you don't want to change the column, you can always convert from Date to Varchar and then (re)convert it.
Example:
First, convert Date to varchar using the style code '112' ISO for formatting as yyyyMMdd:
DECLARE #date DATE = GETDATE();
DECLARE #dateConverted as VARCHAR (8) = (SELECT CONVERT(VARCHAR, #date, 112));
Then you just subtract the month using DATEADD():
DECLARE #previousMonth AS VARCHAR (8) = (SELECT FORMAT(DATEADD(month, -1, #dateConverted), 'yyyyMMdd'));
Finally, convert varchar do Date again:
DECLARE #previousMonthConverted AS DATE = (SELECT CONVERT(CHAR(10), CONVERT(date, #previousMonth), 120));

New to SQL Server looking for assistance for a datetime conversion

this is my first submission on Stack Overflow, and I am open to any suggestions on structuring my questions.
I am new to SQL Server, and I have a line of code I that I don't understand.
Can someone please explain this?
declare #prior_year datetime = convert(date, '12/31/' + convert(varchar, datepart(yy, #start_date) - 1))
This is a problematic way to determine the last day of the year before the date(time) stored in some variable.
convert(date, '12/31/' + convert(varchar, datepart(yy, #start_date) - 1))
In English, working outward:
datepart(yy, #start_date)
Tell me the year of the variable #start_date. This is poor form because, if we mean year, we should spell out YEAR (see "Date Parts" in this post). I said this already once today, but this is just laziness, it's like "I'm going to type just enough characters to avoid an unexpected result, but not enough characters to make my intent clear." Worse is YYYY, which I see often - you have a choice between YYYY and YEAR, why not type the one that's actually a word?
datepart(yy, #start_date) - 1
--------------------------- ^^^
Subtract one from that year.I don't have any issues here, but it may be clearer to use an explicit DATEADD() against the variable first, and then extracting the year from that, since things like <some date thing> - 1 can be misread as an attempt to subtract a day (also covered in the shorthand post referenced above).
convert(varchar, datepart(yy, #start_date) - 1))
--^^^^^^^^^^^^^^^^
Convert that explicitly to a string.
Also poor form here because we should always specify the length of variable-width data. In some cases this can lead to unexpected truncation. See this post.
'12/31/' + convert(varchar, datepart(yy, #start_date) - 1))
--^^^^^^^^^^
Prefix that year with 12/31 to produce a mm/dd/yyyy string.
More poor form, because this then assumes the user has US English regional settings, MDY dateformat, etc. If you're going to insist on building a string that represents a date, always use a standard, unambiguous format: YYYYMMDD. (And FWIW YYYY-MM-DD is ambiguous, try it with SET LANGUAGE FRENCH;). See this post.
convert(date, <the rest>)
Converts the whole expression to a date.
A better solution
Ideally we should not be using strings anywhere along the line for any of this. We have built-in functions that provide all kinds of native date handling capabilities without having to worry about languages, regional settings, date format preferences, or string lengths:
SELECT DATEFROMPARTS(YEAR(#start_date) - 1, 12, 31);
-- or, more explicitly:
SELECT DATEFROMPARTS(DATEPART(YEAR, #start_date) - 1, 12, 31);
The other way you can think about this is that the last day of last year is the same day as the day before the first day of this year. Thinking about it in these terms can make it much easier to conceptualize when you are doing things like prior month, where determining the last day of the previous month is more tedious. Or if you are finding endpoints for range queries, because the end of the current reporting period is never as deterministic as the start of the next reporting period. More on that here.
SELECT DATEADD(DAY, -1, DATEFROMPARTS(YEAR(#start_date), 1, 1));
Also of potential use:
Dating Responsibly
Simplify Date Period Calculations in SQL Server
SQL Server DateTime Best Practices
Four short videos in this series
Reading this from the inside out:
We're first finding the year of the date using DATEPART and then subtracting 1 so for a value for today's date: 2020-08-18 we'd be getting an integer value of 19
datepart(yy, '2020-08-18') - 1)
We're then using convert on that value to change it to a varchar:
convert(varchar, 19)
We're then using that new varchar to create a string:
'12/31/' + '19'
Finally we're using convert again to create a date from the string
convert(date, '12/31/19')
Tony,
For completeness please provide the definition and assignment for #start_date. Assuming the statement you provided works, it is probably defined something like
declare #start_date date
set #start_date = '07-01-2020'
Working from the inside out, we can then break the statement down like so ...
This will extract the year value
datepart(yy, #start_date)
This will subtract 1 from the #start_date year value, assuming 2020, this returns 2019
convert(varchar, datepart(yy, #start_date) - 1)
And then this will convert that to the last day of the previous year.
convert(date, '12/31/' + convert(varchar, datepart(yy, #start_date) - 1))
So the statement simply sets the new field to the last day of the prior year.
declare #prior_year datetime = convert(date, '12/31/' + convert(varchar, datepart(yy, #start_date) - 1))
This SQL code declares a #prior_year datetime variable that is hard coded to 12/31/. datepart is used to extract the previous year from another datetime variable #start_date` that is passed in and tacks the returned value onto the end of the '12/31/' hard coded string. So; its really just a formula of 12/31/(#start_date prior year)
So if #start_date is 8/20/2020
You will end up with the output of 12/31/2019
declare #start_date datetime = getdate()
declare #prior_year datetime = convert(date, '12/31/' + convert(varchar, datepart(yy, #start_date) - 1))
select #prior_year
Result:

How to modify year with a Cast Statement in Sql

I would like to get some help with a CAST SQL Statement
From the below table sample, I would like to modify only the year from 2008 to 2016. Please keep in mind that I need this done with CAST, and not with DATEADD.
DATEADD(YEAR, 8, DATE) would be the solution but if that is not an option please utilize one of the following options.
I have left the DATEADD options in there in case they are usable after all.
DECLARE #d_date DATE = '2008-07-01'
DECLARE #v_date VARCHAR(25) = '2008-07-01'
SELECT #d_date,
#v_date,
DATEADD(YEAR, 8, #d_date),
DATEADD(YEAR, 8, CONVERT(DATE, #v_date)),
DATEADD(YEAR, 8, CAST(#v_date AS DATE)),
CAST(CAST(LEFT(#v_date, 4) AS NUMERIC) + 8 AS VARCHAR(4)) + RIGHT(#v_date, LEN(#v_date) - 4)
Please do not use the last one.
An example of Code.
http://rextester.com/NHHL75120

DATENAME and DATEPART in SQL

I'm trying to get my EntryDate column in this format 'YYYY_m' for example '2013_04'.
This code has been unsuccessful
DATENAME (YYYY, EntryDate) + '_' + DATEPART (M, EntryDate)
Attempts using DATEFORMAT have also been unsuccessful, stating there was syntax error at ',' after the M. What code would work instead?
Thank you.
How about date_format()?
select date_format(EntryDate, '%&Y_%m')
This is the MySQL way. Your code looks like an attempt to do this in SQL Server.
EDIT:
The following should work in SQL Server:
select DATENAME(year, EntryDate) + '_' + RIGHT('00' + DATEPART(month, EntryDate), 2)
Personally, I might use convert():
select replace(convert(varchar(7), EntryDate, 121), '-', '_')
select DATENAME (YYYY, EntryDate)
+ '_'
+ right('0' + convert(varchar(2),datepart (MM, EntryDate)), 2)
You have to convert the result of DATEPART() to a character string in order for the + to perform an append.
FYI - in the future "unsuccessful" doesn't mean anything. Next time post the actual error you are receiving.
For example:
SELECT concat(EXTRACT(YEAR FROM '2015/1/1'), '_',
LPAD(extract(month from '2014/1/1'),2,'0')) AS OrderYear
This uses
concat to combine strings
lpad to place a leading 0 if month is one digit
and uses extract to pick of the part of date needed.
working fiddle
http://sqlfiddle.com/#!2/63b24/8
DATEPART
It is a Datetime function which extract information from date. This function always returns result as integer type.
SELECT DATEPART(month, '2009-01-01 00:00:00:000') as month
it is return "1" as an integer:
DATENAME
It is also another Datetime function which to extract information from date. This function always returns result as varchar
SELECT DATENAME(month, '2009-01-01 00:00:00:000') as month
it is return "January".

Elegantly convert DateTime type to a string formatted "dd-mmm"

We have the following solution:
select
substring(convert(varchar(20),convert(datetime,getdate())),5,2)
+ ' ' +
left(convert(varchar(20),convert(datetime,getdate())),3)
What is the elegant way of achieving this format?
You can do it this way:
declare #date as date = getdate()
select replace(convert(varchar(6), #date, 6), ' ', '-')
-- returns '11-Apr'
Format 6 is dd mon yy and you take the first 6 characters by converting to varchar(6). You just need to replace space with dash at the end.
You can use the dateName function:
select right(N'0' + dateName(DD, getDate()), 2) + N'-' + dateName(M, getDate())
If you really want the mmm part to only have the tree-letter abbreviation of the month, you're stuck with parsing the appropriate conversion type, for example
select left(convert(nvarchar, getDate(), 7), 3)
The problem is that dateName doesn't have an option to get you the abbreviated month, and the abbreviation isn't always just the first three letters (for example, in czech, two months start with Čer). On the other hand, convert 7 always starts with the abbreviation. Now, even with this, I assume that the abbreviation is always three letters long, so it isn't necessarily 100% reliable (you could search for space instead), but I'm not aware of any better option in MS SQL.
DECLARE #t datetime = getdate()
SELECT CONVERT(VARCHAR(24),LEFT(#t,6),113)
Try this...
SELECT LEFT(CONVERT(NVARCHAR(10), GETDATE(), 6), 6)