snippetsqlMajor
How can I get the correct offset between UTC and local times for a date that is before or after DST?
Viewed 0 times
afterlocalcanthebeforeoffsetutcdategetbetween
Problem
I currently use the following to get a local datetime from a UTC datetime:
My problem is that if daylight savings time occurs between
Is there an easy way to convert from utc to local time for a date that is not the current date?
I'm using SQL Server 2005
SET @offset = DateDiff(minute, GetUTCDate(), GetDate())
SET @localDateTime = DateAdd(minute, @offset, @utcDateTime)My problem is that if daylight savings time occurs between
GetUTCDate() and @utcDateTime, the @localDateTime ends up being an hour off.Is there an easy way to convert from utc to local time for a date that is not the current date?
I'm using SQL Server 2005
Solution
The best way to convert a non-current UTC date into local time, prior to SQL Server 2016, is to use the Microsoft .Net Common Language Runtime, or CLR.
The code itself is easy; the difficult part is usually convincing people that the CLR isn't pure evil or scary...
For one of the many examples, check out Harsh Chawla's blog post on the topic.
Unfortunately, there is nothing built-in prior to SQL Server 2016 that can handle this type of conversion, save for CLR-based solutions. You could write a T-SQL function which does something like this, but then you'd have to implement the date-change logic yourself, and I'd call that decidedly not easy.
The code itself is easy; the difficult part is usually convincing people that the CLR isn't pure evil or scary...
For one of the many examples, check out Harsh Chawla's blog post on the topic.
Unfortunately, there is nothing built-in prior to SQL Server 2016 that can handle this type of conversion, save for CLR-based solutions. You could write a T-SQL function which does something like this, but then you'd have to implement the date-change logic yourself, and I'd call that decidedly not easy.
Context
StackExchange Database Administrators Q#28187, answer score: 21
Revisions (0)
No revisions yet.