如何在SQL中从UTC转换为EST



我当前使用的是:

sample_start_time AT TIME ZONE 'UTC' AT TIME ZONE 'Eastern Standard Time' AS sample_start_time_est

发件人:在选择语句中将Datetime列从UTC转换为本地时间

sample_start_time
2021-03-10 21:13:00.000

成为

sample_start_time_est
2021-03-10 16:13:00.000 -05:00

虽然现在显示EST,但我认为系统仍然会根据后续查询的结果将其识别为UTC。如何让系统将调整后的时间识别为EST?

例如:

sample_start_time_est = 2021-03-10 16:14:00.000 -05:00
end_time = 2021-03-10 18:14:00.000
WHERE sample_start_time_est < end_time

上面的WHERE子句当前计算结果为FALSE,但我希望它为TRUE

我正在使用Microsoft SQL Server Management Studio。

CAST(sample_start_time AT TIME ZONE 'UTC' AT TIME ZONE 'Eastern Standard Time' AS DATETIME2) AS sample_start_time_est

您看到的结果之所以出现,是因为datetimeoffset的优先级高于datetime,并且您的比较将强制进行隐式转换。隐式转换将datetime转换为具有零偏移的datetimeoffset

declare @dto_minus5 datetimeoffset = '2022-01-01 00:00:00 -05:00'
declare @later_dt datetime = '2022-01-01 01:00:00'; -- 1 hour later *if* we ignore the offset
declare @later_dt_casted datetimeoffset = cast(@later_dt as datetimeoffset);
select @dto_minus5, @later_dt_casted, iif(@dto_minus5 < @later_dt, 1, 0);
-- produces 2022-01-01 00:00:00 -05:00  2022-01-01 01:00:00 +00:00  0

小提琴;

iif中发生的情况是,@later_dt被提升为datetimeoffset,偏移量为0。然后比较时,会将偏移量考虑在内。也就是说,这两个值是";被带入同一时区";。这意味着我的@dto_minus5值加上5小时(或者等效地,@later_dt减去5小时(。

也就是说,比较:

2022-01-01 00:00:00 -05:002022-01-01 01:00:00

成为的比较

2022-01-01 00:00:00 -05:002022-01-01 01:00:00 +00:00

哪个在同一时区是比较:

2022-01-01 05:00:00 +00:002022-01-01 01:00:00 +00:00

所以前者更大。

要获得所需的语义,可以使用todatetimeoffset()函数:

declare @sample_start_time_est datetimeoffset = '2021-03-10 16:14:00.000 -05:00';
declare @end_time datetime = '2021-03-10 18:14:00.000';
select iif(@sample_start_time_est < todatetimeoffset(@end_time, '-05:00'), 1, 0);
-- prints 1

最新更新