Are UtcNow and Now the same datetime? Do they know they're different?

浪子不回头ぞ 提交于 2020-01-14 09:58:12

问题


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


回答1:


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



回答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




回答3:


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



来源:https://stackoverflow.com/questions/3229326/are-utcnow-and-now-the-same-datetime-do-they-know-theyre-different

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!