1

在我的代码中,我尝试处理 ZoneLocalMapping.ResultType.Ambiguous。线

unambiguousLocalDateTime = localDateTimeMapping.EarlierMapping;

抛出 InvalidOperationException 并显示消息“不应在类型不明确的结果上调用 EarlyMapping 属性”。

我不知道我应该如何处理它。你可以给我一个例子吗?

这就是我的代码的样子:

public Instant getInstant(int year, int month, int day, int hour, int minute)
{
        var localDateTime = new LocalDateTime(year, month, day, hour, minute); //invalidated, might be not existing
        var timezone = DateTimeZone.ForId(TimeZoneId); //TimeZone is set elsewhere, example "Brazil/East"
        var localDateTimeMapping = timezone.MapLocalDateTime(localDateTime);
        ZonedDateTime unambiguousLocalDateTime;
        switch (localDateTimeMapping.Type)
        {
            case ZoneLocalMapping.ResultType.Unambiguous: 
                unambiguousLocalDateTime = localDateTimeMapping.UnambiguousMapping;
                break;
            case ZoneLocalMapping.ResultType.Ambiguous:
                unambiguousLocalDateTime = localDateTimeMapping.EarlierMapping;
                break;
            case ZoneLocalMapping.ResultType.Skipped: 
                unambiguousLocalDateTime = new ZonedDateTime(localDateTimeMapping.ZoneIntervalAfterTransition.Start, timezone);
                break;
            default:
                throw new InvalidOperationException(string.Format("Unexpected mapping result type: {0}", localDateTimeMapping.Type));
        }
        return unambiguousLocalDateTime.ToInstant();
}

如果我查看 ZoneLocalMapping 类,我会看到以下代码:

    /// <summary>
    /// In an ambiguous mapping, returns the earlier of the two ZonedDateTimes which map to the original LocalDateTime.
    /// </summary>
    /// <exception cref="InvalidOperationException">The mapping isn't ambiguous.</exception>
    public virtual ZonedDateTime EarlierMapping { get { throw new InvalidOperationException("EarlierMapping property should not be called on a result of type " + type); } }

这就是我收到异常的原因,但我应该怎么做才能获得 EarlyMapping?

4

1 回答 1

2

看起来您使用的是相对较旧的版本。ZoneLocalMapping从那以后发生了一些变化,我怀疑我已经修复了你发现的错误。这是一个有效的示例:

using System;
using NodaTime;

class Program
{    
    public static void Main()
    {
        var local = new LocalDateTime(2012, 10, 28, 1, 30, 0);
        var zone = DateTimeZone.ForId("Europe/London");
        var mapping = zone.MapLocal(local);

        Console.WriteLine(mapping.Count); // 2
        Console.WriteLine(mapping.First()); // 1.30 with offset +1
        Console.WriteLine(mapping.Last()); // 1.30 with offest +0
    }    
}

由于改进的“解析器”API,您的实际方法现在可以完全消失。您现在可以使用:

private static readonly ZoneLocalResolver CustomResolver =
    Resolvers.CreateMappingResolver(Resolvers.ReturnEarlier,
                                    Resolvers.ReturnStartOfIntervalAfter);

...

Instant instant = zone.ResolveLocal(localDateTime, CustomResolver).ToInstant();
于 2012-06-12T12:53:03.103 回答