c# - 将 DateTime 转换为 UTC 时的调整规则是什么?

标签 c# datetime timezone utc

TimeZoneInfo.ConvertTimeToUtc() 的 MSDN 页面中,有这个信息框:

If the current computer's local time zone includes multiple adjustment rules, this overload of the ConvertTimeToUtc method can return results that differ from the TimeZone.ToUniversalTime and DateTime.ToUniversalTime methods. TimeZone.ToUniversalTime always applies the current adjustment rule to time zone conversion, whether or not dateTime lies within its date range. And when executing on .NET Framework 3.5, DateTime.ToUniversalTime also applies the current adjustment rule to time zone conversion, whether or not dateTime lies within its date range.

我不确定我是否理解这意味着什么。这些调整规则是什么?ConvertTimeToUtc()TimeZone.ToUniversalTime() 的结果有何不同?

最佳答案

这是一个例子。在撰写本文时,我的计算机设置为美国太平洋时区,今天是 2015 年 3 月 2 日。目前是太平洋标准时间(或 PST),比 UTC 晚 8 小时。

DateTime dt = new DateTime(2006, 4, 1, 0, 0, 0);
TimeZoneInfo tzi = TimeZoneInfo.Local;
DateTime utc = TimeZoneInfo.ConvertTimeToUtc(dt, tzi);

在上面的代码中,我将另一个值(2006 年 4 月 1 日午夜)从我的时区转换为 UTC。在那个特定的时间点,太平洋标准时间(或 PST)生效。上面的代码使用了 TimeZoneInfo,这是执行此操作的正确方法。输出是 2006 年 4 月 1 日上午 8:00 UTC。

现在看这段代码:

DateTime dt = new DateTime(2006, 4, 1, 0, 0, 0);
TimeZone tz = TimeZone.CurrentTimeZone;
DateTime utc = tz.ToUniversalTime(dt);

它似乎做几乎相同的事情。但它返回错误值 7:00 AM UTC。

出现这种情况是因为美国changed it's daylight saving time规则于 2007 年生效。在示例中的日期,DST 未根据当时的规则生效,但如果当时的当前规则生效,它将生效。

很简单,TimeZoneInfo 对象知道此更改,但 TimeZone 对象不知道。它错误地假定当前规则始终有效。

TimeZone 类的其他方法也会发生同样的事情,这就是为什么 the MSDN reference说:

Important
Whenever possible, use the TimeZoneInfo class instead of the TimeZone class.

此外,TimeZone 类已从新的 .Net CoreCLR删除项目。

关于“调整规则” - MSDN 的评论具体指的是 TimeZoneInfo.AdjustmentRule类,用于跟踪时区内可能定期或不定期发生的时区偏移量更改。夏令时是一种可能发生的变化类型,但还有其他变化。

您可能希望阅读有关 daylight saving time 的 StackOverflow wiki。和 time zones了解这些变化背后的机制。

您也可以尝试我的 Pluralsight 类(class),Date and Time Fundamentals ,其中更详细地解释了这些概念。

另请参阅:What is the difference between DateTime.ToUniversalTime and TimeZoneInfo.ConvertTimeToUtc?

关于c# - 将 DateTime 转换为 UTC 时的调整规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28808239/

相关文章:

javascript - 如何使用 Javascript Date 对象计算东部时间?

c# - 单个 sql 查询作为数据集中的多个表返回

c# - 使用 Entity Framework Core 对连接表进行多个 OR 的快速查询和过滤

python - 如何按月份和年份输入过滤具有日期时间索引的数据框? Pandas

ruby-on-rails - "First of every month in Ruby"怎么写

mysql - 时区 America/Los_Angeles 和 US/Pacific 和 PST8PDT 之间的区别?

java - 甲骨文/JDBC : retrieving TIMESTAMP WITH TIME ZONE value in ISO 8601 format

c# - 仅当任务未在指定时间内完成时才显示进度对话框

c# - 'call command on property change' 功能应该去哪里?

php - 获取 30 天前的日期并转换为 iso8601 格式