I encountered what may be a leap year in .NET's DateTime
handling, specifically ToLocalTime()
. Here's some code which reproduces the problem (I'm in the Pacific time zone):
DateTime dtStartLocal = DateTime.Parse("2009-02-28T23:00:00.0-08:00");
DateTime dtEndLocal = dtStartLocal.AddYears(3);
DateTime dtStartUtc = dtStartLocal.ToUniversalTime();
DateTime dtEndUtc = dtStartUtc.AddYears(3);
DateTime dtEndLocal2 = dtEndUtc.ToLocalTime();
DateTime dtStartLocal2 = dtStartUtc.ToLocalTime();
Console.WriteLine("START: 1={0}, 2={0}", dtStartLocal, dtStartLocal2);
Console.WriteLine("END : 1={0}, 2={1}", dtEndLocal, dtEndLocal2);
Console.ReadLine();
The output is:
START: 1=2/28/2009 11:00:00 PM, 2=2/28/2009 11:00:00 PM
END : 1=2/28/2012 11:00:00 PM, 2=2/29/2012 11:00:00 PM
Notice the variable which I did ToUniversalTime().AddYears(3).ToLocalTime()
is different than just AddYears(3)
, it's one day ahead.
Has anyone encountered this? If this is expected, can someone explain the logic behind it?
NOTE: Yes, the best approach is to work entirely in UTC and not flip flop between them. This isn't something which is effecting me, but a peculiarity I encountered. Essentially I misunderstood how AddYears()
worked and now I can see why it's doing what it's doing (see my selected answer below).