I have string 20120821 and I need to convert it into 21 AUG 2012 string also. What is easy way?
There's a big list of the different outputs that you can find here.
But to answer your questions:
DECLARE #date VARCHAR(8) = '20120821';
SELECT CONVERT(VARCHAR(11), CONVERT(DATE, #date), 113);
declare #t varchar(50) = '20120821'
select convert(varchar(50),convert(date,#t),113)
You can convert to a date using datefromparts():
select datefromparts(right(ddmmyyyy, 4), substring(ddmmyyyy, 3, 2), left(ddmmyyyy, 2))
Then you can convert to a string:
select convert(varchar(255), datefromparts(right(ddmmyyyy, 4), substring(ddmmyyyy, 3, 2), left(ddmmyyyy, 2)), 106)
Use cast and convert like:
select convert(varchar, cast('20120821' as datetime), 6)
or
select convert(varchar, cast('20120821' as datetime), 113)
Tough this question already have four answers - none of the existing answers is much more than a code dump - so I figured I would add a little explanation.
String representations of dates are considered notorious because a lot of them are ambiguous - For example, 02/04/2019 can be interpreted as either February 4th 2019 or as April 2nd 2019.
It gets worst when you have a two digit year - 01/02/03 can represent so many different dates - including different centuries!
Lucky for you, your source string is in one of the two formats that are guaranteed to always be interpreted correctly by SQL Server when converting to Date (but not to DateTime!):
yyyymmdd is one and yyyy-mm-dd is the other.
Both of these formats are international standard and described in ISO 8601.
Please note, however, that there is a known bug (feature?) in the DateTime data type that makes the yyyy-mm-dd format culture dependent. This bug does not exists in the new and improved alternative data type called DateTime2.
I will not add a code to this answer since it would just be repeating the code from Jim Jimson's answer or from apomene's answer.
Related
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));
I have a varchar column with the following format ddmmyyyy and I'm trying to convert it to date in the format dd-mm-yyyy. I'm using the query below but I get the error:
Conversion failed when converting date and/or time from character string.
select *, coalesce(try_convert(date, newdate, 105), convert(date, newdate))
from mydate
You don't have a date, you have a string. So, you can use string operations:
select stuff(stuff(newdate, 5, 0, '-'), 3, 0, '-')
If you want to convert to a date, you can do:
select convert(date, concat(right(newdate, 4), substring(newdate, 3, 2), left(newdate, 2)))
You could then format this as you want.
However, you should not be converting the value to a date. You should be storing it as a date in the first place.
To turn your string to a date, you can just [try_]cast() it; SQL Server is usually flexible enough to figure out the format by itself:
try_cast(newdate as date)
If you want to turn it back to a string in the target format, then you can use format():
format(try_cast(newdate as date), 'dd-MM-yyyy')
Compared to pure string operations, the upside of the try_cast()/format() approach is that it validates that the string is a valid date in the process.
Have to agree with the others. Why are you storing a date as a string in the first place? In a non-standard format, no less? Here's one way, but you should really fix the data model. Store dates as dates.
DECLARE #badIdea table (dt char(8));
INSERT #badIdea(dt) VALUES('21052020');
SELECT newdate = TRY_CONVERT(date, RIGHT(dt,4) + SUBSTRING(dt,3,2) + LEFT(dt,2))
FROM #badIdea;
BTW 105 won't work because it requires dashes. This works:
SELECT CONVERT(date, '21-05-2020', 105);
That's a bad format too, IMHO, because who knows if 07-08-2020 is July 8th or August 7th. But at least that one is supported by SQL Server. Your current choice is not.
SQL doesn't store date data types in different formats, and it's probably not a good idea to try and adjust this.
If, however, you are wanting a result set to simply display the date in a different format, you are on the right track. You just need to convert your date data type to a string.
SELECT *
, COALESCE ( TRY_CONVERT ( CHAR(10), newdate, 105 ), CONVERT ( CHAR(10), newdate ) )
FROM mydate
Sep-19 (MONTH-YEAR) - varchar
String and what I need to do is change that to:
September 30, 2019 (MONTH DAY(LAST DAY OF THE MONTH),YEAR) varchar
I am working with SQL server 2014.
Any suggestion?
Really, you shouldn't be storing or accepting dates in this format.
But given that you already are, and undoubtedly the response will be that you can't fix it, you can use style 6 (dd MMM yy) and some string manipulation to revert this format back to a proper date. But you have to make sure your language settings match the way the data is stored:
SET LANGUAGE us_english;
DECLARE #my char(6) = 'Sep-19';
SELECT EOMONTH(CONVERT(date, REPLACE('01 '+#my,'-',' '), 6));
I'm really not a big fan of EOMONTH() as this is about the only useful application of it. In my own code I would probably use something like this, even though it's more verbose:
SELECT DATEADD(DAY, -1, DATEADD(MONTH, 1, CONVERT(date, REPLACE('01 '+#my,'-',' '), 6)));
This should work:
select eomonth(cast('01-' + month_year as date))
I'm not a fan of 2 digit years, but this should work for many examples of years.
There are already qite a few good answers, but I'd like to add mine anyway:
declare #input as nvarchar(100) = 'Sep-19'
select FORMAT(EOMONTH(PARSE(LEFT(#input, 3) + '-01-' + RIGHT(#input, 2) as datetime using 'En-Us')), 'MMMM dd, yyyy')
The output is: "September 30, 2019"
I have done my share in converting string to date in SQL Server 2016 but never seen a date with the format like the one below. I have looked online for a possible way to convert it without success. Any help helping me converting the string below to datetime datatype in SQL will be appreciated.
Fri Aug 24 2018 22:28:40
Regards,
Found a way to do it in SQL Server:
select cast(right("string",20) as datetime) as dateColumn
from table
When dealing with non-standard date formats, I usually lookup CONVERT function in SQL Server, as it io very "elastic": you can provide various formats to it, so it recognizes them appropriately.
I use this site for reference. There you can find, that the closest date format is indicated by 100:
0 100 mon dd yyyy hh:miAM/PM Default
It's your format except it doesn't include unnecessary in this case day of week information. So all you need to do is cut out the Fri part:
substring(myDatetimestring, 5, 1000)
or even better
substring(myDatetimeString, charindex(' ', myDatetimeString), 1000)
if the day of week part may have variable length. Don't worry about 1000, it only assures that we will have the rest of the string, not any less.
Now we have proper date format, since it says that it's default, we don't need to supply 100 to convert function and also we can use cast function instead, as you discovered, so we could do:
cast(substring(myDatetimeString, charindex(' ', myDatetimeString), 1000) as datetime)
or
convert(datetime, substring(myDatetimeString, charindex(' ', myDatetimeString), 1000), 100)
or
convert(datetime, substring(myDatetimeString, charindex(' ', myDatetimeString), 1000))
If date is 10/16/2015, column is datetime type '2015-10-16 10:09:19.443'
How to display only the month and year as ' Oct-15' in SQL Server?
If you are using SQL Server 2012 or later, you can use the Format() function:
Declare #Date DateTime = '10/16/2015'
Select Format(#Date, N'MMM-yy')
Result:
Oct-15
Edit - in light of #lad2025's comment, if necessary, you may need to also add the en-US locale:
Declare #Date DateTime = '10/16/2015'
Select Format(#Date, N'MMM-yy', 'en-US')
If you are trying to run a quick ad-hock query to see results formatted as MMM-YY, but do not have access to FORMAT function (i.e. use MS SQL Server 2008 or earlier) you can do this:
SELECT replace(right(convert(varchar(9), date_column, 6), 6), ' ', '-')
FROM my_table
However, if you are writing an application, and would like to present the date to end-user in this specific format, you should do the formatting in the host language.
Here's a pretty simple (and quick) way to convert from DATETIME, although I agree with other comments and answers that a parameter should really be kept in the canonical datetime format, that way any date handling is portable across languages:
SELECT RIGHT(REPLACE(CONVERT(VARCHAR(9), CAST('2015-10-16 10:09:19.443' AS DATETIME), 6), ' ', '-'),6) AS [Mon-YY]
Look at DatePart method in SQLServer and extract in postgreSQL.