Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert historic dates from utc to local time

I have an sql table with data like this:

| theDate (datetime)  | theValue (int) |
----------------------------------------
| 2010-05-17 02:21:10 |              5 |
| 2009-03-12 04:11:35 |             23 |
| 2010-02-19 18:16:53 |             52 |
| 2008-07-07 22:54:11 |             30 |

The dates are stored in UTC format in a datetime column, how can I convert them to local time (Norway)? Remember that the UTC-offset is not the same all year because of winter/summer-time.

UPDATE: I am using Microsoft SQL Server 2005, and I need to do this from SQL because the data will be shown to a report later on.

like image 258
Espo Avatar asked May 20 '10 10:05

Espo


2 Answers

This statement will work against the table you listed. Using the logic you can apply it to any date fields.

    SELECT CASE
         WHEN [theDate] BETWEEN 
         Convert(DATETIME, Convert(VARCHAR(4), Year([theDate])) + '-03-' + Convert(VARCHAR(2), (31 - (5 * Year([theDate])/4 + 4) % 7)) + ' 02:00:00', 20)
         AND
         Convert(DATETIME, Convert(VARCHAR(4), Year([theDate])) + '-10-' + Convert(VARCHAR(2), (31 - (5 * Year([theDate])/4 + 1) % 7)) + ' 03:00:00', 20)
         THEN Dateadd(hh, 2, [theDate])
         ELSE Dateadd(hh, 1, [theDate])
       END AS [theDate],
       [theValue]
FROM   [YOURTABLE] 
like image 154
Kenneth Avatar answered Sep 19 '22 02:09

Kenneth


Write you CLR function that will convert your SqlDateTime from UTC to your CLR local, something like this:

[Microsoft.SqlServer.Server.SqlFunction]
public static SqlDateTime ToLocalTime(SqlDateTime dt)
{
    try
    {
         return TimeZone.CurrentTimeZone.ToLocalTime(dt.Value);
    }
    catch
    {
        return SqlDateTime.Null;
    }
}
like image 29
Slawomir Brys Avatar answered Sep 22 '22 02:09

Slawomir Brys