McGuireV10
McGuireV10

Reputation: 9936

Convert discrete non-UTC date/time parts to a UTC DateTimeOffset

When using Noda Time, is there a more direct way to go from a set of discrete non-UTC values (that is to say, separate year, month, day, hour, minute values) to a UTC DateTimeOffset variable? I'm doing the following in a loop and it seems a bit odd to create LocalDateTime then apply two different timezones in a row.

DateTimeOffset target = 
    new LocalDateTime(year, month, day, hour, minute)
        .InZoneStrictly(dataTimeZone)
        .WithZone(utcTimeZone)
        .ToDateTimeOffset();

I realize I'm probably overthinking/micro-optimizing, but since I'm new to Noda Time I'm mostly asking in case there is a way with fewer steps or that is better in some way. (I'm aware InZoneStrictly can throw exceptions, this is actually related to a scheduling system, so I definitely don't want invalid or auto-adjusted results.)

Upvotes: 2

Views: 73

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241563

Your implementation is fine, though you could use DateTimeZone.Utc instead of utcTimeZone.

Here's another implementation that will give the same results:

DateTimeOffset target =
    new LocalDateTime(year, month, day, hour, minute)
        .InZoneStrictly(dataTimeZone)
        .ToInstant()
        .ToDateTimeOffset();

You might consider whether you actually need DateTimeOffset or not. Unless you're calling to some other API that requires one, you could use an OffsetDateTime or just an Instant instead.

As for the part about InZoneStrictly, consider that a user might pass in a perfectly valid set of date and time values that just happen to be ambiguous within the given time zone because they represent a local time during a backward transition (either for DST or change in standard time). Do you really want to throw in such cases?

Also, consider that if you have logic that applies a daily recurrence for the same time on multiple days, eventually you could run into an invalid time during the gap of a forward transition (again either for DST or change in standard time).

In Noda Time 2.x, InZoneLeniently was updated to generally do the right thing in such scenarios (first occurrence of ambiguous values, skip ahead for invalid values). Scheduling was a primary use case in this decision.

Upvotes: 3

Related Questions