简体   繁体   中英

SQL - Converting String to Date and Time

I need to convert a value to a SQL Server DateTime .

Data looks like below :

  • 20161021-12:55:16.000
  • 20161021-13:22:09.974

I tried

CONVERT(DATE, '20161021-12:55:16.000', 102) 

and it throws an error.

Can I get help in SQL to convert these samples into a valid date time?

Also these values are in UTC.

I need to convert them to EST.

Appreciate your help.

If you're confident with your format being consistent then you can just take that dash out (I've used datetime for illustration purposes);

CONVERT(DATETIME, REPLACE('20161021-12:55:16.000','-',' '), 102) 

Result

2016-10-21 12:55:16.000

For the conversion you can convert to datetime, take off your hours and then convert to the date format you want;

CONVERT(DATETIME, DATEADD(hh,-5,CONVERT(DATETIME,REPLACE('20161021-12:55:16.000','-',' '))), 102)

Result;

2016-10-21 07:55:16.000

To get a better idea of this, set it before 5am and you will get the previous day;

CONVERT(DATETIME, DATEADD(hh,-5,CONVERT(DATETIME,REPLACE('20161021-04:55:16.000','-',' '))), 102)

Result

2016-10-20 23:55:16.000

For reference, on my test systems you don't need to convert to 102, that's the default.

DATEADD(hh,-5,CONVERT(DATETIME,REPLACE('20161021-04:55:16.000','-',' ')))

To get the time difference dynamically do something like this;

DATEADD(hh,DATEDIFF(hh,GETUTCDATE(),GETDATE()),CONVERT(DATETIME,REPLACE('20161021-04:55:16.000','-',' ')))

No need for the CONVERT 102.

Select cast(replace('20161021-12:55:16.000','-',' ') as datetime)

Returns

2016-10-21 12:55:16.000

To Convert From UTC to Local Server. One should keep in mind that the time difference will change with Daylight Savings Time (EDT/EST)

Select DateAdd(MINUTE,DateDiff(MINUTE,GetUTCDate(),GetDate()),cast(replace('20161021-12:55:16.000','-',' ') as datetime))

Reuturns

2016-10-21 07:55:16.000

Try this...

select CONVERT(DATETIME, replace('20161021-12:55:16.000','-',' '), 102) 

For EST

select dateadd(HH,-5,CONVERT(DATETIME, replace('20161021-12:55:16.000','-',' '), 102))
 SELECT CONVERT(datetime,SWITCHOFFSET(CONVERT(datetimeoffset, 
                                REPLACE('20161021-12:55:16.000','-',' ')), 
                        DATENAME(TzOffset, SYSDATETIMEOFFSET()))) 
   AS ColumnInLocalTime

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM