5

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

Community
  • 1
  • 1
Scott Stafford
  • 43,764
  • 28
  • 129
  • 177

3 Answers3

6

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
LukeH
  • 263,068
  • 57
  • 365
  • 409
  • 1
    I didn't try it, but mostly because I was surprised that the question wasn't on SO already and thought it would be a useful one for people. And maybe a touch of laziness, but I swear, mostly good intentions! ;) – Scott Stafford Jul 12 '10 at 14:51
  • The key test I want to see maybe is, is the result of "Console.WriteLine(utcNow.ToUniversalTime() == utcNow);"... – Scott Stafford Jul 12 '10 at 14:52
  • 2
    +1. Additionally, there is a different `DateTimeKind`. There is a `ToLocalTime()` for the other direction. Be careful with `DateTimeKind.Undefined`, these times are always converted (`ToUniversalTime` treats them as local time, `ToLocalTime` as UTC). – Stefan Steinegger Jul 12 '10 at 14:57
2

Also be wary of taking a local DateTime and calling .ToUniversalTime() when daylight savings comes around.

See the note in the remarks section here: http://msdn.microsoft.com/en-us/library/system.timezone.touniversaltime.aspx

Matt Glover
  • 1,347
  • 7
  • 13
0

DateTime.Now returns the system time while DateTime.UtcNow returns the UTC time.

jean27
  • 701
  • 8
  • 25