Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Ticks, DateTime.Equals and timezones

Tags:

date

c#

datetime

How come the following code (in C#) returns false :

DateTime d = DateTime.Now;
d.Ticks == d.ToUniversalTime().Ticks; // false

I'd expect the ticks of a DateTime to be based on UTC time. The MSDN page on DateTime.Ticks mentions says

The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.

Midnight on January first, 0001 .. in which timezone ?

Why would DateTime.Ticks be timezone dependant ?

I guess that the fact that the Ticks are different is why the following code also returns false

DateTime d = DateTime.Now;
d == d.ToUniversalTime(); // false

The MSDN doc on DateTime.Equals mentions

t1 and t2 are equal if their Ticks property values are equal. Their Kind property values are not considered in the test for equality.

My expectation was that DateTime.Ticks would be equal, no matter the timezone.

I'd expect two moments in time to be equal no matter on what timezone they happened. Are my expectations wrong ?

like image 335
GuiSim Avatar asked Apr 20 '12 18:04

GuiSim


2 Answers

source: http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/fde7e5b0-e2b9-4d3b-8a63-c2ae75e316d8

DateTime.Ticks is documented as "number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001". That is 1-Jan-0001 local time. If you convert your DateTime to UTC, Ticks will then be number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001 UTC. Potentially different that 1-Jan-0001 local time, ergo the two Ticks values will be different.

like image 197
Habib Avatar answered Oct 20 '22 15:10

Habib


Your current Datetime (unless you live in the one specific time zone - GMT) is offset from the UTC time by x hours, so DateTime.Now might put you at 4 AM while Datetime.Now.ToUniversalTime() could be at 11 PM depending on your current time zone.

The Ticks are calculated after the conversion from your time zone to universal time, so the only time they should be equal is if you live in the GMT time zone.

Put more simply, the number of ticks between 1/1/2011 8:00 AM is not the same as the number of ticks since 1/1/2011 11:00 PM. In your code, the date is being converted to the universal date, and then ticks being calulated on the right side of the equation, but it's just using your local date to get the difference on the left, hence, they're != each other.

like image 23
David Avatar answered Oct 20 '22 15:10

David