我的机器正在PDT上,如果我说DateTime.Now,那么我将得到一个本地时间,该时间等于2012年9月18日6:00:00 AM。我想获得与此datetime实例等效的UTC。 UTC时间将比PDT提前7小时,比PST提前8小时。我想自动考虑夏令时。
My machine is on PDT and if I say DateTime.Now, then I will get a local time which is say equivalent to Sep-18th 2012 6:00:00 AM. I want to get UTC equivalent for this datetime instance. UTC time will be 7 hours ahead Of PDT and 8 hours ahead of PST. I want to consider daylight saving automatically.
关于如何执行此操作的任何想法?
Any idea on how I can do this?
推荐答案您可以使用
var now = DateTime.UtcNow;要转换现有的DateTime,假设它具有时区信息,您可以使用 DateTime.ToUniversalTime()。如果您使用以下方式获取DateTime实例:
To convert an existing DateTime, assuming it has time zone information, you can use DateTime.ToUniversalTime(). If you get the DateTime instance using e.g.
var localNow = DateTime.Now; // Has timezone info它将具有时区信息。如果您创建它,例如
it will have time zone information. If you create it e.g. using a tick count, it will not contain timezone information unless you explicitly supply it.
var unspecifiedNow = new DateTime(someTickCount); // No timezone info值得一提的是,.NET中的时区处理不是最佳的。您可能希望看看 Noda Time (由乔恩·斯凯特),如果您需要做一些涉及时区的详细说明。
It is worth mentioning that timezone handling in .NET is not optimal. You may wish to have a look at Noda Time (a project by Jon Skeet) if you need to do anything elaborate involving time zones.
更多推荐
如何在C#中获取本地时间的UTC等效值
发布评论