【问题标题】:TimeZoneInfo - AdjustmentRule error on .net core 1.1TimeZoneInfo - .net core 1.1 上的 AdjustmentRule 错误
【发布时间】:2017-08-31 16:54:10
【问题描述】:

我有一段代码可以让我获取当前日期/时间(本地)。

它将在 Azure 上运行。

我正在获取通用时间并将其转换为英国当地时间(考虑到 BST - 英国夏令时)。

在从 .NET 4.6.1/Core 项目迁移到 .NET Core 1.1 时,我现在遇到了一个错误。

类型中不存在类型名称“AdjustmentRule” '时区信息'

“TimeZoneInfo”不包含“GetAdjustmentRules”的定义 并且没有扩展方法“GetAdjustmentRules”接受第一个 可以找到“TimeZoneInfo”类型的参数(您是否缺少 使用指令还是程序集引用?)

仅使用 .NET Core 1.1 - 我该如何解决这个问题?

public static DateTime GetLocalDateTimeNow()
{
    DateTime localDate = System.DateTime.Now.ToUniversalTime();

    // Get the venue time zone info
    TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
    TimeSpan timeDiffUtcClient = tz.BaseUtcOffset;
    localDate = System.DateTime.Now.ToUniversalTime().Add(timeDiffUtcClient);

    if (tz.SupportsDaylightSavingTime && tz.IsDaylightSavingTime(localDate))
    {
        TimeZoneInfo.AdjustmentRule[] rules = tz.GetAdjustmentRules();
        foreach (var adjustmentRule in rules)
        {
            if (adjustmentRule.DateStart <= localDate && adjustmentRule.DateEnd >= localDate)
            {
                localDate = localDate.Add(adjustmentRule.DaylightDelta);
            }
        }
    }

    DateTimeOffset utcDate = localDate.ToUniversalTime();

    return localDate;
}

我不介意替换实现,只要它考虑到 BST 并在 .net core 1.1(没有 4.6.1)上运行。

【问题讨论】:

    标签: c# .net azure asp.net-core asp.net-core-mvc


    【解决方案1】:

    您不需要自己执行任何操作 - 只需请求 TimeZoneInfo 进行转换即可。这就是它的用途!

    // Only need to do this once...
    private static readonly TimeZoneInfo londonZone =
        TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
    
    public static DateTime GetUkDateTimeNow() =>
        TimeZoneInfo.ConvertTime(DateTime.UtcNow, londonZone);
    

    几点说明:

    • 我已将 GetLocalDateTimeNow() 重命名为 GetUkDateTimeNow(),以表明它始终处理英国时区,而不是特定用户或计算机的本地时区
    • 在 Unix 上,您需要请求 "Europe/London" 而不是 "GMT Standard Time"
    • 要使其独立于任何这些 - 并且实际上独立于系统本地时区数据 - 您可以使用我的 Noda Time project,我认为它会为您提供更简洁的代码。

    几乎没有人需要在他们的代码中处理AdjustmentRule。我在 Noda Time 做,因为我需要能够将 TimeZoneInfo 区域表示为 Noda Time DateTimeZone 对象,但这很不寻常。如果您曾经确实需要使用它们,它们会比您预期的要复杂得多,并且在 .NET 实现中出现过多次错误;我目前(就像今天一样)正在解决 Mono 实现中的错误......

    顺便说一句,我强烈敦促您不要在任何地方使用DateTime.Now。始终使用DateTime.UtcNow,如果您确实需要,然后转换为系统本地时区。

    【讨论】:

    • 如果不难描述,你能说为什么我们不应该使用DateTime.Now吗?
    • @RufusL:理论上,它可能是有损的 - UTC 到本地日期/时间的转换可能会丢失数据,因为多个 UTC 时间可以映射到同一个本地时间。这也是低效的 - 系统时钟实际上是 UTC,因此您当前正在从 UTC 映射到本地并再次返回。
    • @RufusL:实际上,无论原始值是否在 DST 中,转换都会在其 Kind 支持字段中“记住”。有关详细信息,请参阅codeblog.jonskeet.uk/2012/05/02/more-fun-with-datetime。但最好还是不要这样做:)
    • 谢谢,这很有趣也很有帮助
    猜你喜欢
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    • 2011-06-26
    • 2018-06-07
    • 2017-09-29
    相关资源
    最近更新 更多