If I run a snippet like:
bool areTheyTheSame = DateTime.UtcNow == DateTime.Now
what will I get? Does the DateTime returned know its timezone such that I can compare?
My specific problem is that I'm trying to build a cache-like API. If it takes a DateTime AbsoluteExpiration, do I have to enforce that users of my API know whether to give me a UTC time or a timezone-based time?
[Edit] This SO question is extremely relevant to my issue as well: Cache.Add absolute expiration - UTC based or not?
[Edit] Just to clarify for future readers, the DateTimeKind is what is different. The Undefined DateTimeKind's are often a problem, which is what you get when you pull one out of a database, for instance. Set the DateTimeKind in the DateTime constructor...
[Edit] JonSkeet wrote a lovely blog post condemning this behavior and offering a solution: http://noda-time.blogspot.co.uk/2011/08/what-wrong-with-datetime-anyway.html
Did you actually try the snippet yourself?
They're different, and a straight comparison doesn't account for the difference, but you can convert local to UTC by calling ToUniversalTime
.
var now = DateTime.Now;
var utcNow = DateTime.UtcNow;
Console.WriteLine(now); // 12/07/2010 16:44:16
Console.WriteLine(utcNow); // 12/07/2010 15:44:16
Console.WriteLine(now.ToUniversalTime()); // 12/07/2010 15:44:16
Console.WriteLine(utcNow.ToUniversalTime()); // 12/07/2010 15:44:16
Console.WriteLine(now == utcNow); // False
Console.WriteLine(now.ToUniversalTime() == utcNow); // True
Console.WriteLine(utcNow.ToUniversalTime() == utcNow); // True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With