Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String to Datetime2

I am trying to convert

@string='25/05/2016 09:00' 

to 2016-05-25 09:00.

@string is concatenation of @string2='25/05/2016' and @string3='09:00'

When I try to do this using

CONVERT(datetime, '25/05/2016 09:00') 

I get the following error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

Please help, thanks.

like image 915
Avinash Avatar asked Aug 09 '16 04:08

Avinash


People also ask

What is format of DATETIME2?

The DATETIME2 data type specifies a date and time with fractional seconds. DATETIME2 supports dates from 0001-01-01 through 9999-12-31. The default value is 1900-01-01 00:00:00. The time is based on a 24-hour clock.

Is DATETIME2 better than datetime?

Microsoft recommends using DateTime2 instead of DateTime as it is more portable and provides more seconds precision. Also, DateTime2 has a larger date range and optional user-defined seconds precision with higher accuracy.

What is DATETIME2 data type in SQL Server?

The DateTime2 is an SQL Server data type, that stores both date & time together. The time is based on the 24 hours clock. The DateTime2 stores the fractional seconds Up to 7 decimal places (1⁄10000000 of a second). The Precision is optional and you can specify it while defining the DateTime2 column.


1 Answers

Try this:

SELECT CONVERT(datetime2, '25/05/2016 09:00', 103) 

The convert method takes 3 arguments: The first is the target data type, the second is the expression to convert, and the third is the style. In this case, 103 stands for British or French date format, which is dd/mm/yyyy.

Declare @string char(10)='25/05/2016'
Declare @string2 char(5)='09:00'

SELECT CONVERT(datetime2, @string + ' ' + @string2, 103) 

Result: 2016-05-25 09:00:00.0000000 (datetime2)

like image 87
Zohar Peled Avatar answered Sep 30 '22 01:09

Zohar Peled