Framework问题与RTZ2时区

Framework问题与RTZ2时区

本文介绍了.Net Framework问题与RTZ2时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎我们在.Net Framework 4.5中发现了RTZ2时区(俄罗斯标准时间)问题。

It seems we have found an issue with RTZ2 timezone (Russian Standard Time) in .Net Framework 4.5.

如果您尝试在2014-01- 01 00:00:00和2014-01-01 00:59:59(在RTZ2时区)到UTC,您将收到错误:提供的DateTime表示无效时间。例如,当时钟向前调整时,跳过的时间段中的任何时间都是无效的。

If you try to convert time between 2014-01-01 00:00:00 and 2014-01-01 00:59:59 (in RTZ2 timezone) to UTC, you get an error: The supplied DateTime represents an invalid time. For example, when the clock is adjusted forward, any time in the period that is skipped is invalid.

示例():

var rtz2 = TimeZoneInfo.FindSystemTimeZoneById("Russian Standard Time");
var moment = new DateTime(2014, 1, 1);
var utc = TimeZoneInfo.ConvertTimeToUtc(moment, rtz2); // throws an exception

有什么办法解决此问题吗?

Any ideas how to fix this?

推荐答案

这可能与,已由.NET 4.6修复。

This is probably related to KB3012229, which was fixed with .NET 4.6.

如果已安装.NET 4.6,则不会抛出异常-即使您定位到.NET 4.0到4.5.2-因为它们都是就地升级。

If you have .NET 4.6 installed, the exception will not be thrown - even if you are targeting .NET 4.0 through 4.5.2 - because they are all in-place upgrades.

在.NET 3.5或更高版本上会重现 例外。如果未安装.NET 4.6,则通过.NET 4.5.2进行.NET 4.0。

The exception does reproduce on .NET 3.5, or on .NET 4.0 through .NET 4.5.2 if you do not have .NET 4.6 installed.

您可以在此处执行以下操作:

There are a few things you can do here:


  • 选项1:保持您的代码不变,并更新到最新的.NET 4.6(或安装其中一个KB文章中现已提供修补程序)

  • Option 1: Leave your code as-is, and update to the latest .NET 4.6 (or install one of the hotfixes now available in the KB article)

选项2:更改代码以使用如下功能:

Option 2: Change your code to use a function such as this:

private DateTime Rtz2ToUtc(DateTime dt)
{
    if (dt.Kind == DateTimeKind.Utc)
        return dt;

    if (dt.Year < 2011)
    {
        var tz = TimeZoneInfo.FindSystemTimeZoneById("Russian Standard Time");
        return TimeZoneInfo.ConvertTimeToUtc(dt, tz);
    }

    var transition = new DateTime(2014, 10, 26, 2, 0, 0);
    var offset = TimeSpan.FromHours(dt < transition ? 4 : 3);
    return new DateTimeOffset(dt, offset).UtcDateTime;
}


  • 选项3:使用和时区:

    private DateTime Rtz2ToUtc(DateTime dt)
    {
        if (dt.Kind == DateTimeKind.Utc)
            return dt;
    
        DateTimeZone tz = DateTimeZoneProviders.Tzdb["Europe/Moscow"];
        LocalDateTime ldt = LocalDateTime.FromDateTime(dt);
        return ldt.InZoneLeniently(tz).ToDateTimeUtc();
    }
    


  • 我个人更喜欢选项3,因为TZDB时区比Windows时区准确得多。您可以在中阅读更多内容。

    Personally, I prefer Option 3, as TZDB time zones are much more accurate than Windows time zones. You can read more in the timezone tag wiki.

    这篇关于.Net Framework问题与RTZ2时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-29 01:03