In SQL Server 2008, how do I convert a string of type 'MMMM DD,YYYY' (i.e. June 01, 2013) to a regular datetime type (20130601)?
As far as I know, Convert() only works to convert dates into strings, not the other way around. I'm sure there's a standardized answer somewhere, but I can't find one for SQL Server. Should I write a custom procedure to parse the string?
While it's not recommended to store your date in string formats, you still could properly convert string to date. When you know exact format, avoid using cast and use convert - see possible formats here.
set language english
select convert(datetime, 'June 01, 2013', 107)
-----------------------
2013-06-01 00:00:00.000
Conversion from and to 107 format depends on your connection settings. If, for example, your connection language is not english, you could get an error
set language norwegian
select convert(datetime, 'June 01, 2013', 107)
-----------------------
Msg 241, Level 16, State 1, Line 2
Conversion failed when converting date and/or time from character string.
Related
How can one convert the string "01 December 2016" to a date type in SQL Server?
CONVERT(date, '01 December 2016', 106)
Expected date outcome "01 Dec 2016"
If 2012+ you can use Format()
Select Format(convert(date,'01 December 2016'),'dd MMM yyyy')
Returns
01 Dec 2016
It is very dangerous to work with culture specific date/time formats and it is even worse to work with language and culture specific formats...
If ever possible store date/time values in appropriate types!
In my (german) system a direct cast or convert would break due to "December", which is "Dezember" in Germany. Have a look at this:
SET LANGUAGE English; --try the same with "German"
DECLARE #d VARCHAR(100)='01 December 2016';
SELECT CONVERT(VARCHAR(11),CONVERT(DATE,#d,106),106);
The result
01 Dec 2016
One should never rely on implicit conversions: Call CONVERT with the third parameter in any case!
The third parameter 106 tells SQL Server the date's format (how to parse it). The first CONVERTSs target type is DATE. This - now properly represented! - date can be converted again to VARCHAR(11) with 106 as third parameter now specifying the output format.
For deeper insight in language specific date parts you can run this query:
SELECT * FROM sys.syslanguages;
btw: If you are using SQL Server 2012+ you should call FORMAT() as pointed out by John Cappelletti
Have researched a lot, both on this site, and others, but still don't have a valid solution. I have a column of varchar datatype, it contains DateTime data. I need to store only the Date portion in a Date type column. Tried different ways of Cast, Convert, and other functions, but still haven't been able to make it work.
Basically I want to convert this
Tue Apr 26 2016 13:54:53 GMT+0200 (CEST)
to
04/26/2016
Assuming your Day and Month part is always 3 characters long this can be done simply as this:
DECLARE #d VARCHAR(100)='Tue Apr 26 2016 13:54:53 GMT+0200 (CEST)';
SELECT CONVERT(DATE,SUBSTRING(#d,4,12),109);
If this was to easy one would have to find the blank(s) with CHARINDEX, but I don't think so...
The format code 109 means mon dd yyyy hh:mi:ss:mmmAM (or PM) Details here.
And be aware that formats containing language depending parts are directly sent by the devil to create never ending pain... This will not work on a server with a different language setting!
Declare #String varchar(max) = 'Tue Apr 26 2016 13:54:53 GMT+0200 (CEST)'
Select cast(Substring(#String,12,4)+Substring(#String,4,7) as date)
Returns
2016-04-26
Okay a few things here you have a field that looks to be psuedo ISO 8601 but is not the standard. The first question will be: "Where does this come from?" Typically you don't have the 'Tue' or 'GMT' or '(CEST)' in a standard and the offset from Greenwich Meantime is in the format (+/-)##:## NOT (+/-)####. SQL and many other formats can easily accept a standardized string in the ISO 8601 format. Good brief here: https://www.w3.org/TR/NOTE-datetime
That being said you can easily get what you want with a little know how:
DECLARE
#S VARCHAR(128) = 'Tue Apr 26 2016 13:54:53 GMT+0200 (CEST)'
, #Valid VARCHAR(128)
--Legitimate ISO 8601 string:
SELECT #Valid = RTRIM(LTRIM(REPLACE(STUFF(STUFF(#S, 1, 4, ''), LEN(#S)-12, 12, ':00'), 'GMT', '')))
SELECT #Valid
--Legitimate DateTimeOffset
SELECT CAST(#Valid AS DATETIMEOFFSET)
--Now that I have a legimiate DateTimeOffset I can downconvert easily
SELECT CAST(CAST(#Valid AS DATETIMEOFFSET) AS DATE)
--AND... Now that I have a legimate Date I can format it many different ways
SELECT CONVERT(VARCHAR, CAST(CAST(#Valid AS DATETIMEOFFSET) AS DATE), 101)
The real thing to realize here is there is magical conversion of DateTime using the convert function. But you may be wondering 'what if I want it to look different?'. Try this page:
http://www.sql-server-helper.com/tips/date-formats.aspx
I would be leery though of just finding the placement of were things appear to be coming from a string even though I can parse your example. If you are getting things not following a standard you should know why. The main reason being you may be able to get this to work for a specific instance but not be able to repeat this pattern over and over.
I can't make out from the documentation why SQL Server parses a text in a format other than the specified style.
Regardless of whether I provide text in the expected format:
SELECT CONVERT(DATETIME, N'20150601', 112)
or incorrect format (for style 113):
SELECT CONVERT(DATETIME, N'20150601', 113)
The results are the same: 2015-06-01 00:00:00.000 I would expect the latter to fail to convert the date (correctly).
What rules does it employ when trying to convert a VARCHAR to DATETIME? I.e. why does the latter (incorrect format style) still correctly parse the date?
EDIT: It seems I've not been clear enough. Style 113 should expect dd mon yyyy hh:mi:ss:mmm(24h) but it happily converts values in the format yyyymmdd for some reason.
Because the date is in a canonical format ie(20150101). The database engine falls over it implicitly. This is a compatibility feature.
If you swapped these around to UK or US date formats, you would receive conversion errors, because they cannot be implicitly converted.
EDIT: You could actually tell it to convert it to a pig, and it would still implicitly convert it to date time:
select convert(datetime,'20150425',99999999)
select convert(datetime,'20150425',100)
select convert(datetime,'20150425',113)
select convert(datetime,'20150425',010)
select convert(datetime,'20150425',8008135)
select convert(datetime,'20150425',000)
And proof of concept that this is a compatibility feature:
select convert(datetime2,'20150425',99999999)
Although you can still implicitly convert datetime2 objects, but the style must be in the scope of the conversion chart.
Reason why is the date N'20150601' converted to valid datetime is because of fact that literal N'20150601' is universal notation of datetime in SQL Server. That means, if you state datetime value in format N'yyyymmdd', SQL Server know that it is universal datetime format and know how to read it, in which order.
You should convert to varchar type in order to apply those formats:
SELECT CONVERT(varchar(100), CAST('20150601' as date), 113)
OK, you are converting datetime to datetime. What did you expect? In order to apply formats you should convert to varchar and you have to have date or time type as second parameter.
I am trying to convert a date in mm/dd/yyyy format
select convert(date,'31/12/2013',101)
but I'm getting this error
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
How to do this? My system (Windows 7) has a dd-mm-yyyy format.. will system date format will have any impact on it?`
see
http://msdn.microsoft.com/en-us/library/ms187928.aspx
101 is the US style (mm/dd/yyyy)
try 103 (dd/mm/yyyy) which is British/French
SELECT CONVERT(DATE, '31/12/2013', 103)
Style 101 is the US style, so this has months first - your string represents the 12th day of the 31st month ....
What you need to use is style 103 (British/French) which uses the day first - so this string is 31st of December:
SELECT CONVERT(DATE, '31/12/2013', 103)
See the official MSDN SQL Server Books Online Documentation on CAST and CONVERT and what styles are defined and what they mean
I have a varchar(200) column called Submit_Date and I am trying to convert it to MM/DD/YYYY format. When I do that I get the following error:
Msg 242, Level 16, State 3, Line 1The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Sample Data of the table is:
Submit_Date
-----------------------
27-09-2013 16:15:00 CST
30-09-2013 16:30:24 CST
27-09-2013 10:03:46 CST
I tried the following:
Select Convert(datetime,Submit_date,101) from dbo.Tickets
You've committed about 15 cardinal sins about date/time here. First, the quick answer:
DECLARE #x VARCHAR(200);
SELECT #x = '27-09-2013 16:15:00 CST'
SELECT CONVERT(CHAR(10),CONVERT(DATETIME,LEFT(#x,10),105),101);
Next:
Why on earth are you storing date/time data in a varchar(200) column? You are aware that anyone can insert values like '09-27-2013' or '465-32-207floob' in there, right? If you need time zone information you can look at the DATETIMEOFFSET data type (but note that it is not DST-aware).
Why are you storing a regional format like dd-mm-yyyy? If the first value were 07-11-2013 I'd have to guess if you meant July 11 or November 7. If you're not going to do it right and use a proper date/time data type, why use a string format that makes people guess? You are much better off with a format that is unambiguous, such as yyyy-mm-ddThh:mm:ssZ.
Similarly, why are you outputting a different regional format like mm/dd/yyyy? If you output '05/06/2013' are you 100% confident that everyone in your audience will know you meant May 6 and not June 5? Your output should be unambiguous as well. If you absolutely must format in some regional and ambiguous format, use the string formatting capabilities of your client. For example, C# has .ToString() and .Format() which are much more powerful and efficient in presenting dates with string formats that T-SQL will ever be.
try the following SQL query to achieve the expected result:
SELECT convert(varchar, convert(date, '27-09-2013 16:15:00', 105), 101)