是UtcNow现在同样的日期时间?他们知道他们有什么不同? [英] Are UtcNow and Now the same datetime? Do they know they're different?

查看:774
本文介绍了是UtcNow现在同样的日期时间?他们知道他们有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我运行像一个片段:

 布尔areTheyTheSame = DateTime.UtcNow == DateTime.Now 

我将要得到什么?请问日期时间返回知道它的时区,这样我可以比较?



我的具体问题是,我想建立一个缓存一样API。如果需要一个DateTime AbsoluteExpiration,我必须执行我的API的用户知道能否给我一个UTC时间或基于时区时间?



这太问题是我的问题高度相关,以及: Cache.Add绝对过期 - 基于UTC还是不



只是为了澄清对未来的读者,在DateTimeKind是有什么不同?未定义DateTimeKind的往往是一个问题,这是当你拉一明一数据库,比如你会得到什么。设置在DateTimeKind DateTime构造...



JonSkeet写了一个可爱的博客文章谴责这种行为,并提供一个解决方案:的 http://noda-time.blogspot.co.uk/2011/08 /what-wrong-with-datetime-anyway.html


解决方案

你真的自己尝试片段<? / p>

他们是不同的,直的比较不占的差异,但你可以通过调用的 ToUniversalTime

  VAR现在= DateTime.Now; 
VAR utcNow = DateTime.UtcNow;

Console.WriteLine(现在的); // 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(现== utcNow); //假
Console.WriteLine(now.ToUniversalTime()== utcNow); //真
Console.WriteLine(utcNow.ToUniversalTime()== utcNow); //真


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

这篇关于是UtcNow现在同样的日期时间?他们知道他们有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆