I have a few columns in an SQL server 2008 R2 database that i need to convert from local time (the time zone the sql server is in) to UTC.
I have seen quite a few similar questions on StackOverflow, but the answers all fail to work correctly with daylight saving time, they only take into account the current difference and offset the date.
I could not find any way at all doing this using T-SQL alone. I solved it using SQL CLR:
public static class DateTimeFunctions
{
[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static DateTime? ToLocalTime(DateTime? dateTime)
{
if (dateTime == null) return null;
return dateTime.Value.ToLocalTime();
}
[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static DateTime? ToUniversalTime(DateTime? dateTime)
{
if (dateTime == null) return null;
return dateTime.Value.ToUniversalTime();
}
}
And the following registration script:
CREATE FUNCTION ToLocalTime(@dateTime DATETIME2) RETURNS DATETIME2 AS EXTERNAL NAME AssemblyName.[AssemblyName.DateTimeFunctions].ToLocalTime;
GO
CREATE FUNCTION ToUniversalTime(@dateTime DATETIME2) RETURNS DATETIME2 AS EXTERNAL NAME AssemblyName.[AssemblyName.DateTimeFunctions].ToUniversalTime;
It is a shame to be forced to go to such effort to convert to and from UTC time.
Note, that these functions interpret local time as whatever is local to the server. It is recommended to have clients and servers set to the same time zone to avoid any confusion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With