如何在C#中获取本地时间的UTC等效值

编程入门 行业动态 更新时间:2024-10-25 06:24:19
本文介绍了如何在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等效值

本文发布于:2023-11-16 16:21:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1605899.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间   如何在   等效值   UTC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!