What is this about adjustment rules when converting DateTime to UTC?

后端 未结 1 628
说谎
说谎 2021-01-19 04:20

In the MSDN page for TimeZoneInfo.ConvertTimeToUtc(), there is this info box:

If the current computer\'s local time zone includes multiple adjustment

1条回答
  •  一生所求
    2021-01-19 04:24

    Here's an example. My computer at the time of writing this post is set to the US Pacific time zone, and today is March 2, 2015. It is currently Pacific Standard Time (or PST), which is 8 hours behind UTC.

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

    In the above code, I am converting another value, midnight April 1st 2006, from my time zone to UTC. At that particular point in time, Pacific Standard Time (or PST) was in effect. The above code uses TimeZoneInfo, and is the correct way to do this. The output is April 1st 2006 at 8:00 AM UTC.

    Now look at this code:

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

    It would appear to do almost the same thing. But it returns an incorrect value of 7:00 AM UTC.

    This occurs because the United States changed it's daylight saving time rules effective 2007. On the date in the example, DST was not in effect by the rule that was in place at that time, but it would be in effect if the current rule was in place then.

    Quite simply, the TimeZoneInfo object is aware of this change, but the TimeZone object is not. It mistakenly assumes the current rule was always in effect.

    The same thing will occur with other methods on the TimeZone class, which is why the MSDN reference says:

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

    Also, the TimeZone class has been removed from the new .Net CoreCLR project.

    Regarding "adjustment rules" - the MSDN remark is referring specifically to the TimeZoneInfo.AdjustmentRule class, which is used to track changes to time zone offsets that can occur on a regular or irregular basis within a time zone. Daylight Saving Time is one such type of change that can occur, but there are others as well.

    You may wish to read the StackOverflow wikis about daylight saving time and time zones to understand the mechanics behind these changes.

    You might also try my Pluralsight course, Date and Time Fundamentals, which explains these concepts in even greater detail.

    See also: What is the difference between DateTime.ToUniversalTime and TimeZoneInfo.ConvertTimeToUtc?

    0 讨论(0)
提交回复
热议问题