UtcNow 和 Now 是相同的日期时间吗?他们知道自己与众不同吗?
如果我运行这样的片段:
bool areTheyTheSame = DateTime.UtcNow == DateTime.Now
我会得到什么?返回的 DateTime 是否知道它的时区以便我可以比较?
我的具体问题是我正在尝试构建一个类似缓存的 API。如果需要 DateTime AbsoluteExpiration,我是否必须强制 API 的用户知道是给我 UTC 时间还是基于时区的时间?
[编辑] 这个问题也与我的问题极其相关:缓存.添加绝对过期时间 - 是否基于 UTC?
[编辑] 只是为了向未来的读者澄清,DateTimeKind 有何不同。未定义的 DateTimeKind 通常是一个问题,例如,当您从数据库中提取一个时会遇到这种情况。在 DateTime 构造函数中设置 DateTimeKind...
[编辑] JonSkeet 写了一篇可爱的博客文章谴责这种行为并提供解决方案: http://noda-time.blogspot.co.uk/2011/08/what-wrong-with-datetime-anyway.html
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您自己实际上尝试过该片段吗?
它们是不同的,直接比较并不能解释差异,但您可以通过调用
ToUniversalTime
。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
.另外,在夏令时到来时,请注意获取本地
DateTime
并调用.ToUniversalTime()
。请参阅此处备注部分中的注释:http://msdn。 microsoft.com/en-us/library/system.timezone.touniversaltime.aspx
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
DateTime.Now 返回系统时间,而 DateTime.UtcNow 返回 UTC 时间。
DateTime.Now returns the system time while DateTime.UtcNow returns the UTC time.