Search code examples
c#.netdatetimetimezonedst

Does .NET DateTime.ToLocalTime persist across DST changes?


In the UK the clocks changed on 25/10/2015

If I ran the code below on 24/10/2015 and again on 26/10/2015, would the same output be produced?

From my knowledge of how the DateTime stuff works in C# I am assuming yes but I wanted to double check as it is critical for my application.

// January date outside of DST
var januaryDate = new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc);
Console.WriteLine(januaryDate.ToLocalTime().ToString());

// April date inside DST
var aprilDate = new DateTime(2015, 4, 1, 0, 0, 0, DateTimeKind.Utc);
Console.WriteLine(aprilDate.ToLocalTime().ToString());

Solution

  • ToLocalTime uses the current timezone's rules, not just the current offset to calculate local time. Calling ToLocalTime on 2015-01-01 00:00 and 2015-04-01 00:00 will return the same result whether the call is made before or after a DST change.

    My current offset is +2, but calling the sample code returns 1/1/2015 2:00:00 am in the first case and 1/4/2015 3:00:00 am in the second.

    Checking the reference source for ToLocalTime shows that the method checks whether DST needs to be applied for a specific date before returning the local time:

    Boolean isDaylightSavings = false;
    Boolean isAmbiguousLocalDst = false;
    Int64 offset = TimeZoneInfo.GetUtcOffsetFromUtc(this, TimeZoneInfo.Local,
                               out isDaylightSavings, out isAmbiguousLocalDst).Ticks;
    
    long tick = Ticks + offset;
    //various validations
    //...
    return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst);