How to convert CST to UTC in MSSQL

1.3k Views Asked by At

Is it possible to convert CST to UTC in MSSQL?

For example:

convert Thu May 13 11:14:19 CST 2021 to 2021-05-13 11:14:19.000

2

There are 2 best solutions below

1
On BEST ANSWER

On the fly conversion:

DECLARE @CstTime    varchar(30) = 'Thu May 13 11:14:19 CST 2021'

DECLARE @MonthList  varchar(35) = 'JanFebMarAbrMayJunJulAugSepOctNovDec'
DECLARE @Month      varchar( 2)         
DECLARE @Year       varchar( 4) 
;

SET     @CstTime    =   STUFF(@CstTime,1,4,'')
SET     @Month      =   RIGHT('00' + LTRIM((CHARINDEX(LEFT(@CstTime, 3), @MonthList)+2)/3), 2)
SET     @CstTime    =   REPLACE(@CstTime, ' CST ', '')
SET     @CstTime    =   STUFF(@CstTime,1,4,'-'+@Month+'-')
SET     @Year       =   RIGHT(@CstTime, 4)
SET     @CstTime    =   REPLACE(@CstTime, @Year, '')
SET     @CstTime    =   @Year + '-' + @CstTime

SELECT  @CstTime
0
On

As I mentioned in the comment, assuming your value is a datetimeoffset (and why wouldn't it be, it's a date and time value with a time zone), you can use AT TIME ZONE to change the time zone of a value. With a single value, this would like this:

DECLARE @YourDate datetimeoffset(0) = '2021-05-13T11:14:19-08:00';
SELECT @YourDate AT TIME ZONE 'UTC';

db<>fiddle