How to convert a string to date T-SQL?

How to convert String to Date in T-SQL?

My test case is the line: '24.04.2012'

+82
tsql sql-server-2005
Apr 24 2018-12-12T00:
source share
6 answers
 CONVERT(datetime, '24.04.2012', 104) 

Gotta do the trick. See here for more information: "CAST and CONVERT (Transact-SQL)"

+129
Apr 24 '12 at 19:15
source share

Microsoft SQL Date Formats

 CONVERT(DateTime, DateField, 104) 
+25
Apr 24 '12 at 19:05
source share

The solution works well here. The main statement contains a built-in try-parse method:

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

Here 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 for internal database tracking only.

See also these Microsoft MSDN links:

+17
Feb 10 '16 at 15:18
source share

Although CONVERT works, you should not actually use it. You should ask yourself why you parse string values ​​in SQL-Server. If this is a one-time task in which you manually correct some data, you will not receive this data another time, this is normal, but if any application uses this, you must change something. A better way would be to use the date data type. If this is user input, it is even worse. Then you first need to perform a client check. If you really want to pass string values ​​where SQL-Server expects a date, you can always use the ISO format ("YYYYMMDD"), and it should be automatically converted.

+8
Sep 19 '12 at 17:18
source share

You can use:

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

Reference: CAST and CONVERT (Transact-SQL)

+4
Apr 24 '12 at 19:18
source share
 CONVERT(DateTime, ExpireDate, 121) AS ExpireDate 

will do what is necessary, the result:

 2012-04-24 00:00:00.000 
0
Oct 30 '17 at 3:28
source share



All Articles