TimeZone使用TSQL进行转换

时间:2011-07-06 10:40:22

标签: sql-server tsql timezone sql-server-2008-r2 utc

我有传入的小时数据(跨越5年),时间戳记录在CST或EST中。我想在UTC时间将它存储在我的数据库中。

有没有办法让我使用TSQL从CST / CDT / CPT或EST / EDT / EPT转换为UTC?

2 个答案:

答案 0 :(得分:2)

mI建议您将这些存储为DATETIMEOFFSET以保留时区信息。

如果您需要显示为UTC日期,则可以使用SWITCHOFFSET

答案 1 :(得分:1)

您可以在EST或EDT中确定行的日期时间:

  

Since 2007, the local time changes at 02:00 EST to 03:00 EDT on the second Sunday in March and returns at 02:00 EDT to 01:00 EST on the first Sunday in November, in the U.S. as well as in Canada

然后应用DATEADD()

我的源代码更好地解释了我的意思:

declare @t table(dt datetime)

insert @t values ('2011-07-06T10:00:00'), ('2011-01-01T00:00:00'), ('2011-03-12T00:00:00'),
    ('2006-07-06T10:00:00')

select b.dt
    , CASE
        WHEN b.dt between b.[edt_start] and [edt_end] 
            THEN DATEADD(HH, -5, b.dt)
        ELSE DATEADD(HH, -4, b.dt)
    END

    , CASE
        WHEN b.dt between b.[edt_start] and [edt_end] 
            THEN '-05:00'
        ELSE '-04:00'
    END

from
(
    select a.dt
        , DATEADD(HH, 2, CASE 
            WHEN DATEPART(WEEKDAY, a.march) = 1 
                THEN a.march 
            ELSE DATEADD(DAY, 15 - DATEPART(WEEKDAY, a.march), a.march) 
        END) [edt_start]

        , DATEADD(HH, 2, CASE 
            WHEN DATEPART(WEEKDAY, a.november) = 1 
                THEN a.march 
            ELSE DATEADD(DAY, 8 - DATEPART(WEEKDAY, a.november), a.november) 
        END) [edt_end]
    from
    (
        select t.dt
            , YEAR(t.dt) [year]
            , CAST(CAST(YEAR(t.dt) as varchar(4)) + '03' + '01' as datetime) [march]
            , CAST(CAST(YEAR(t.dt) as varchar(4)) + '11' + '01' as datetime) [november]
        from @t t
    )a
)b