How to parse string into date?

TsqlSql Server-2005

Tsql Problem Overview


How can I convert a String to a Date in T-SQL?

My test case is the string: '24.04.2012'

Tsql Solutions


Solution 1 - Tsql

CONVERT(datetime, '24.04.2012', 104)

Should do the trick. See here for more info: CAST and CONVERT (Transact-SQL)

Solution 2 - Tsql

Microsoft SQL Date Formats

CONVERT(DateTime, DateField, 104)

Solution 3 - Tsql

Assuming that the database is MS SQL Server 2012 or greater, here's a solution that works. The basic statement contains the in-line try-parse:

SELECT TRY_PARSE('02/04/2016 10:52:00' AS datetime USING 'en-US') AS Result;

Here's what we implemented in the production version:

UPDATE dbo.StagingInputReview
 SET ReviewedOn = 
     ISNULL(TRY_PARSE(RTrim(LTrim(ReviewedOnText)) AS datetime USING 'en-US'), getdate()),
 ModifiedOn = (getdate()), ModifiedBy = (suser_sname())
 -- Check for empty/null/'NULL' text
 WHERE not ReviewedOnText is null 
   AND RTrim(LTrim(ReviewedOnText))<>''
   AND Replace(RTrim(LTrim(ReviewedOnText)),'''','') <> 'NULL';

The ModifiedOn and ModifiedBy columns are just for internal database tracking purposes.

See also these Microsoft MSDN references:

Solution 4 - Tsql

Although the CONVERT thing works, you actually shouldn't use it. You should ask yourself why you are parsing string values in SQL-Server. If this is a one-time job where you are manually fixing some data you won't get that data another time, this is ok, but if any application is using this, you should change something. Best way would be to use the "date" data type. If this is user input, this is even worse. Then you should first do some checking in the client. If you really want to pass string values where SQL-Server expects a date, you can always use ISO format ('YYYYMMDD') and it should convert automatically.

Solution 5 - Tsql

You can use:

SELECT CONVERT(datetime, '24.04.2012', 103) AS Date

Reference: CAST and CONVERT (Transact-SQL)

Solution 6 - Tsql

CONVERT(DateTime, ExpireDate, 121) AS ExpireDate

will do what is needed, result:

2012-04-24 00:00:00.000

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNazar TereshkovychView Question on Stackoverflow
Solution 1 - TsqlChris RobertsView Answer on Stackoverflow
Solution 2 - TsqltherealmitchconnorsView Answer on Stackoverflow
Solution 3 - TsqlMAbraham1View Answer on Stackoverflow
Solution 4 - TsqlEricView Answer on Stackoverflow
Solution 5 - TsqlSeann AlexanderView Answer on Stackoverflow
Solution 6 - TsqlJMMS KarunarathneView Answer on Stackoverflow