2012-06-12 118 views
1

在我的代碼中,我嘗試處理ZoneLocalMapping.ResultType.Ambiguous。行如何正確處理ZoneLocalMapping.ResultType.Ambiguous?

unambiguousLocalDateTime = localDateTimeMapping.EarlierMapping; 

投用消息一個InvalidOperationException「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); } } 

這就是爲什麼我收到的例外,但我應該怎麼做早期搜索?

回答

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(); 
+0

酷!非常感謝你。 – RWC

+0

(此刻)可以在這裏找到最新的源代碼:http://code.google.com/p/noda-time/source/checkout – RWC