如何在C#中获取本地时间的UTC等效值 [英] How to get UTC equivalent for my local time in C#

查看:308
本文介绍了如何在C#中获取本地时间的UTC等效值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的机器正在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等效值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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