Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime difference operator considers daylight saving?

As far as I know the difference operator of the DateTime type considers leap years: so

new DateTime(2008, 3, 1) - new DateTime(2008, 2, 1) // should return 29 days
new DateTime(2009, 3, 1) - new DateTime(2009, 2, 1) // should return 28 days

But what about daylight saving?

like image 967
Michael Damatov Avatar asked May 01 '09 08:05

Michael Damatov


2 Answers

.NET does not handle daylight savings time correctly, even though it gives answers you want. You want incorrect answers.

Short version:

  • How can .NET know that in 1977 daylight savings time was in effect the entire year, due to the energy crisis?

  • How can .NET know what the daylight savings rules will be in Israel, when the rules are decided year-to-year by the Knesset?

  • How is .NET to know that the US ran on DST year round during WWII, and from 1945 to 1966 the DST rules varied region to region, and the rules still do vary region to region.

.NET tries a cop-out, and uses the current daylight savings rules, even if they weren't, or will be, in effect. The result is that you get answers which, while are what you think you want, are incorrect.

From Raymond Chen's blog entry, Why Daylight Savings Time is nonintuitive:

Why don't the (win32) time zone conversion functions use the time zone appropriate for the time of year?

...

Win32 does not attempt to guess which time zone rules were in effect at that other time. So Win32 says, "Thursday, October 17, 2002 8:45:38 AM PST".

Note: Pacific Standard Time. Even though October 17 was during Pacific Daylight Time, Win32 displays the time as standard time because that's what time it is now.

.NET says, "Well, if the rules in effect now were also in effect on October 17, 2003, then that would be daylight time" so it displays "Thursday, October 17, 2003, 9:45 AM PDT" - daylight time.

So the answers you get are wrong. But since you expect the wrong answer, it's what you get.

like image 190
Ian Boyd Avatar answered Sep 17 '22 15:09

Ian Boyd


I don't think it will. The documentation simply says that a DateTime is stored as the number of ticks since 12:00:00 midnight, January 1, 0001, but it doesn't say in which TimeZone the midnight actually is - I would have to assume that if it was always stored internally in UTC, they would say so.

You can easily get around this though: Just do:

var difference = Dt1.ToUniversalTime() - Dt2. ToUniversalTime()

and the conversions to UTC will take into account daylight savings

like image 41
Orion Edwards Avatar answered Sep 16 '22 15:09

Orion Edwards