C# 将本地时间转换为 UTC
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16652153/
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
Converting Local Time To UTC
提问by Mark Hardin
I'm up against an issue storing datetimes as UTC and confused why this does not yield the same result when changing timezones:
我遇到了将日期时间存储为 UTC 的问题,并困惑为什么在更改时区时这不会产生相同的结果:
var dt = DateTime.Parse("1/1/2013");
MessageBox.Show(TimeZoneInfo.ConvertTimeToUtc(dt, TimeZoneInfo.Local).ToString());
I am manually switching my local time zone on the machine between eastern and central.
我正在东部和中部之间手动切换机器上的本地时区。
Central yields 1/1/2013 6:00:00 AM, and Eastern yields 1/1/2013 5:00:00 AM. What am I missing here? They should be the same regardless of the time zone, correct?
中部收益率1/1/2013 6:00:00 AM,东部收益率1/1/2013 5:00:00 AM。我在这里缺少什么?无论时区如何,它们都应该相同,对吗?
Thanks so much in advance!
非常感谢!
采纳答案by Charlie Kilian
I think what you are missing is that the DateTimereturned by your DateTime.Parse()statement doesn't come with a time zone. It's just a date and time that can be in any time zone. When you call TimeZoneInfo.ConvertTimeToUtc(dt, TimeZoneInfo.Local), you are telling it which time zone it starts in. So if you start in Central, you will get one answer, whereas if you start in Eastern, you will get an answer that is an hour earlier, UTC. Indeed, this is what your code shows.
我认为您缺少的是DateTime您的DateTime.Parse()声明返回的内容没有时区。它只是一个日期和时间,可以在任何时区。当您调用 时TimeZoneInfo.ConvertTimeToUtc(dt, TimeZoneInfo.Local),您会告诉它它在哪个时区开始。因此,如果您从 Central 开始,您将得到一个答案,而如果您从 Eastern 开始,您将得到比 UTC 早一个小时的答案。确实,这就是您的代码显示的内容。
回答by AD.Net
There is a .ToUtc()method for DateTimeclass
有一个类的.ToUtc()方法DateTime
回答by paparazzo
This is midnight
这是午夜
var dt = DateTime.Parse("1/1/2013");
Midnight in eastern and central is not the same absolute time.
That is the whole purpose of time zones.
东部和中部的午夜绝对时间不一样。
这就是时区的全部目的。
回答by Yanga
You can use NodaTime:
您可以使用NodaTime:
static string LocalTimeToUTC(string timeZone, string localDateTime)
{
var pattern = LocalDateTimePattern.CreateWithInvariantCulture("dd/MM/yyyy HH:mm:ss");
LocalDateTime ldt = pattern.Parse(localDateTime).Value;
ZonedDateTime zdt = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZone]);
Instant instant = zdt.ToInstant();
ZonedDateTime utc = instant.InUtc();
string output = utc.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
return output;
}
回答by pintu sharma
When you have trouble with converting to local time to UTC then just remove the last keyword of index and then convert to UtcDateTime
当您无法将本地时间转换为 UTC 时,只需删除 index 的最后一个关键字,然后转换为 UtcDateTime
NewsDate = DateTimeOffset.Parse(data.NewsDate.Remove(data.NewsDate.LastIndexOf("IST"))).UtcDateTime;

