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
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.