Search code examples
c#dstdatetime-conversion

Converting DateTimes that are near DayLight Savings time?


I'm working on software that runs reports for GPS devices that are running 24/7/365. Part of the report output requires that we convert our stored database times (kept in Central Standard Time) to user timers (any requested time zone). Twice a year we run into an issue with DST when people run reports that start before and finish after the time change. It fails at one line:

return TimeZoneInfo.ConvertTime(dateToConvert, DatabaseTime, UserTime);

dateToConvert is a DateTime to be converted. DatabaseTime and UserTime are both TimeZoneInfo objects. I'm not doing anything tricky or complicated but DateTimes near the DST time change throw exceptions. Such as 3/10/2013 2:02:11 AM even though it's being "converted" from Central Time to Central Time.

What is the best method for handling DateTimes near DST time changes?


Solution

  • Conversion should work properly as the time is not truly junk, as Hans stated, rather it is just non-adjusted (a term I just invented). 3/10/2013 2:02:11 AM CDT == 3/10/2013 8:02:11 AM UTC == 3/10/2013 3:02:11 AM CDT...they are ALL semantically equivalent. If you do not believe me, do the conversion at timeanddate.com and see they all equate (round to nearest 5 minutes for their calculator though). Whether .NET code will allow this semantic equivalence, I have not tried it because I am not in front of my dev box currently.

    UPDATE #1:

    Run the following code on a computer set to CST time zone:

    using System;
    
    namespace TimeZoneSample
    {
        public static class Program
        {
            public static void Main()
            {
                DateTime t = DateTime.Parse("3/10/2013 2:02:11 AM");
                Console.WriteLine(t);
                Console.WriteLine(t.ToUniversalTime());
                Console.WriteLine(t.ToUniversalTime().ToLocalTime());
            }
        }
    }
    

    This yields the following console output:

    3/10/2013 2:02:11 AM
    3/10/2013 8:02:11 AM
    3/10/2013 3:02:11 AM
    

    Proof that my original explanation is correct. quod erat demonstrandum