Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string to date in sql server

Tags:

How do I convert YYYY-MM-DD (2012-08-17) to a date in SQL Server?

I don't see this format listed on the help page: http://msdn.microsoft.com/en-us/library/ms187928.aspx

like image 578
birdy Avatar asked Nov 07 '12 20:11

birdy


People also ask

Can we convert string to date in SQL?

In SQL Server, converting a string to date explicitly can be achieved using CONVERT(). CAST() and PARSE() functions.

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.


1 Answers

I think style no. 111 (Japan) should work:

SELECT CONVERT(DATETIME, '2012-08-17', 111) 

And if that doesn't work for some reason - you could always just strip out the dashes and then you have the totally reliable ISO-8601 format (YYYYMMDD) which works for any language and date format setting in SQL Server:

SELECT CAST(REPLACE('2012-08-17', '-', '') AS DATETIME) 
like image 149
marc_s Avatar answered Sep 21 '22 21:09

marc_s