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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12483084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:24:12  来源:igfitidea点击:

How to get UTC equivalent for my local time in C#

c#datetime

提问by Amit

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.

我的机器在 PDT 上,如果我说 DateTime.Now,那么我会得到一个本地时间,相当于 2012 年 9 月 18 日 6:00:00 AM。我想获得此日期时间实例的 UTC 等效值。UTC 时间将比 PDT 早 7 小时,比 PST 早 8 小时。我想自动考虑夏令时。

Any idea on how I can do this?

关于我如何做到这一点的任何想法?

采纳答案by Eric J.

You can use

您可以使用

var now = DateTime.UtcNow;

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.

要转换现有的 DateTime,假设它有时区信息,您可以使用DateTime.ToUniversalTime()。如果您使用例如获取 DateTime 实例

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

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.

值得一提的是,.NET 中的时区处理不是最佳的。?如果您需要做任何涉及时区的复杂工作,您可能希望查看Noda TimeJon Skeet 的一个项目)。

回答by Dean Kuga

Use DateTime.ToUniversalTimeMethod.

使用日期时间。ToUniversalTime方法。

回答by Miguel Angelo

If you want to convert any date from your time-zone to UTC do this:

如果要将时区中的任何日期转换为 UTC,请执行以下操作:

TimeZone.CurrentTimeZone.ToUniversalTime(myLocalDateTime)

If you want to convert it back from UTC:

如果要将其从 UTC 转换回:

TimeZone.CurrentTimeZone.ToLocalTime(myUtcDateTime)