我如何正确处理ZoneLocalMapping.ResultType.Ambiguous?

时间:2012-06-12 10:38:06

标签: c# nodatime

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

unambiguousLocalDateTime = localDateTimeMapping.EarlierMapping;

抛出InvalidOperationException,并显示消息“不应在类型为Ambiguous的结果上调用EarlierMapping属性”。

我不知道应该如何处理它。你能举个例子吗?

这就是我的代码:

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); } }

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

1 个答案:

答案 0 :(得分: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();