views:

66

answers:

2

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: http://stackoverflow.com/questions/1688554/cache-add-absolute-expiration-utc-based-or-not

+2  A: 

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
@LukeH: 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
@LukeH: The key test I want to see maybe is, is the result of "Console.WriteLine(utcNow.ToUniversalTime() == utcNow);"...
Scott Stafford
+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
@Scott: I've edited the answer to include it.
LukeH
A: 

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

jean27