将 CURRENT_TIMESTAMP 从 UTC 转换为 EST

Convert CURRENT_TIMESTAMP from UTC to EST

我试图在查询的开头声明一个日期时间变量,该变量保存查询的 运行 时间。我正在拉 UTC 时间,但我需要 EST。

我试过下面的代码:

DECLARE @RunDate as datetimeoffset  
SET @RunDate = CURRENT_TIMESTAMP at time zone 'Eastern Standard Time'  

DECLARE @RunDateEST as datetime  
SET @RunDateEST = CONVERT(DATETIME, SWITCHOFFSET(@RunDate, DATEPART(tz, SYSDATETIMEOFFSET())))  

SELECT @RunDate as runDate, @RunDateEST as runDateEST  

但收到以下内容:

Actual Result (adds 4 hours to UTC time):  
    runDate:       2019-07-31 13:34:01.2770000 -04:00  
    runDateEST:    2019-07-31 17:34:01.277  

有谁知道我的查询缺少什么会达到以下结果?

Expected Result (subtract 4 hours from UTC time):  
    runDate:        2019-07-31 13:34:01.2770000 -04:00  
    runDateEST:     2019-07-31 09:34:01.277  

您可以尝试以下方法:

DECLARE @RunDateUTC as datetimeoffset  
SET @RunDateUTC = CURRENT_TIMESTAMP AT TIME ZONE 'UTC' 

DECLARE @RunDateEST as datetime  

SET @RunDateEST = CONVERT(DATETIME, @RunDateUTC AT TIME ZONE 'Eastern Standard Time')

SELECT @RunDateUTC,@RunDateEST

精简版

使用单个:

select cast(SYSDATETIMEOFFSET() at time zone 'Eastern Standard Time' as datetime)

说明

问题是首先使用 CURRENT_TIMESTAMPCURRENT_TIMESTAMP 等同于 GETDATE()。它 returns 本地 datetime 没有任何偏移指示。 这意味着

select  CURRENT_TIMESTAMP at time zone 'Eastern Standard Time'

等同于

select  GETDATE() at time zone 'Eastern Standard Time'

在这种情况下,AT TIME ZONE 只是附加偏移量而不进行任何转换。它什么也做不了,因为它不知道源偏移是什么。这是文档中的 clearly explained :

Converts an inputdate to the corresponding datetimeoffset value in the target time zone. When inputdate is provided without offset information, the function applies the offset of the time zone assuming that inputdate is in the target time zone. If inputdate is provided as a datetimeoffset value, then AT TIME ZONE clause converts it into the target time zone using the time zone conversion rules.

我怀疑服务器的时区是 UTC,这意味着 SWITCHOFFSET 必须 添加 4 小时到 EST 时间以获得正确的 UTC 时间。

要解决此问题,请使用 SYSDATETIMEOFFSET() 而不是 GETDATE/CURRENT_TIMESTAMP :

select SYSDATETIMEOFFSET() at time zone 'Eastern Standard Time' 

这个returns:

2019-08-01 07:05:23.5447068 -04:00

要去除偏移量,将结果转换为 datetime :

select cast(SYSDATETIMEOFFSET() at time zone 'Eastern Standard Time' as datetime)

这个returns:

2019-08-01 07:05:23.543