How to calculate the local datetime from a utc datetime in tsql (sql 2005)?

前端 未结 10 1351
Happy的楠姐
Happy的楠姐 2021-02-02 14:13

i want to loop over a period of time in tsql, and print the utc datetimes and our local variant. We live in UTC +1, so i could easily add 1 hour, but in the summertime we live i

10条回答
  •  南方客
    南方客 (楼主)
    2021-02-02 14:59

    This solution seems too obvious.

    If you can get UTC Date with GETUTCDATE() and you can get your local date with GETDATE() you have an offset that you can apply for any datetime

    SELECT DATEADD(hh, DATEPART(hh, GETDATE() - GETUTCDATE()) - 24, GETUTCDATE()) 
    

    this should return the local time you executed the query,

    SELECT DATEADD(hh, DATEPART(hh, GETDATE() - GETUTCDATE()) - 24, N'1/14/2011 7:00:00'  ) 
    

    this will return 2011-01-14 02:00:00.000 because i'm in UTC +5

    Unless I'm missing something?

提交回复
热议问题