Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to date in specific format

How do I convert a string to a date type in SQL Server 2008 R2?

My string is formatted dd/mm/yyyy

I tried this

SELECT CAST('01/08/2014' AS DATE)

But that does the cast in mm/dd/yyyy format.

like image 605
Petah Avatar asked Dec 12 '22 04:12

Petah


2 Answers

You need the convert function, where you can specify a format code:

select convert(datetime, '01/08/2014', 103)

The 103 means dd/mm/yyyy. See the docs.

like image 57
Blorgbeard Avatar answered Dec 27 '22 13:12

Blorgbeard


Dateformat.

SET DATEFORMAT DMY ;
SELECT cast('01/08/2014' as date) ;

Convert.

SELECT convert(date, '01/08/2014', 103 ) ;

And for completeness, SQL Server 2012 and later has the following.

SELECT parse('01/08/2014' as date using 'en-NZ' ) ;
like image 39
Greenstone Walker Avatar answered Dec 27 '22 13:12

Greenstone Walker