Thứ Tư, 19 tháng 4, 2023

[SQL Server] Convert DateTimeOffset to DateTime

declare @dateTime datetime2 = SYSDATETIME()
declare @dateTimeOffset datetimeoffset = SYSDATETIMEOFFSET()
 
select @dateTime as [CurrentDateTime],
@dateTimeOffset as [CurrentDateTimeOffset],
CAST(@dateTimeOffset as datetime2) as [DateTime1]


select CAST('2023-04-19 15:32:31.2721255 +07:00' as datetime2) -- Output: 2023-04-19 15:32:31.2721255
select CAST('2023-04-19 15:32:31.2721255 +08:00' as datetime2) -- Output: 2023-04-19 15:32:31.2721255

select SWITCHOFFSET('2023-04-19 15:32:31.2721255 +07:00', '+01:00') -- Output: 2023-04-19 09:32:31.2721255 +01:00
select SWITCHOFFSET('2023-04-19 15:32:31.2721255 +08:00', '+01:00') -- Output: 2023-04-19 08:32:31.2721255 +01:00

select CAST(SWITCHOFFSET('2023-04-19 15:32:31.2721255 +07:00', '+01:00') as datetime2) -- Output: 2023-04-19 09:32:31.2721255
select CAST(SWITCHOFFSET('2023-04-19 15:32:31.2721255 +08:00', '+01:00') as datetime2) -- Output: 2023-04-19 08:32:31.2721255