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

前端 未结 10 1344
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 15:08

    I recently had to do the same thing. The trick is figuring out the offset from UTC, but it's not a hard trick. You simply use DateDiff to get the difference in hours between local and UTC. I wrote a function to take care of this.

    Create Function ConvertUtcDateTimeToLocal(@utcDateTime DateTime)
    Returns DateTime
    Begin
        Declare @utcNow DateTime
        Declare @localNow DateTime
        Declare @timeOffSet Int
    
        -- Figure out the time difference between UTC and Local time
        Set @utcNow = GetUtcDate()
        Set @localNow = GetDate()
        Set @timeOffSet = DateDiff(hh, @utcNow, @localNow) 
    
        DECLARE @localTime datetime 
    
        Set @localTime = DateAdd(hh, @timeOffset, @utcDateTime) 
    
        -- Check Results
        return @localTime 
    
    End
    GO
    

    This does have on crucial short coming: If a time zone uses a fractional offset, such as Nepal which is GMT+5:45, this will fail because this only deals with whole hours. However, it should fit your needs just fine.

提交回复
热议问题