How do I correcly handle ZoneLocalMapping.ResultType.Ambiguous?

Posted by RWC on Stack Overflow See other posts from Stack Overflow or by RWC
Published on 2012-06-12T10:38:06Z Indexed on 2012/06/12 10:40 UTC
Read the original article Hit count: 251

Filed under:
|

In my code I try to handle ZoneLocalMapping.ResultType.Ambiguous. The line

unambiguousLocalDateTime = localDateTimeMapping.EarlierMapping;

throws an InvalidOperationException with message "EarlierMapping property should not be called on a result of type Ambiguous".

I have no clue how I should handle it. Can you give me an example?

This is what my code looks like:

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

If I look at class ZoneLocalMapping I see the following code:

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

That's why I am receiving the exception, but what should I do to get the EarlierMapping?

© Stack Overflow or respective owner

Related posts about c#

Related posts about nodatime