Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OffsetTime in NodaTime

Tags:

c#

.net

nodatime

I'm looking for some kind of OffsetTime support in NodaTime, but am not seeing anything. I am receiving data in a format such as "17:13:00+10:00". I am to treat this as a time offset, applying it to a given date (which the user is in control of) to arrive at a local time for display purposes.

The best I've been able to come up with is this:

// the date for this OffsetDateTime will be 1/1/2000
var parsed = OffsetDateTimePattern.CreateWithInvariantCulture("HH:mm:sso<G>").Parse(input).Value;

var desiredLocalDate = new LocalDate(2017, 06, 13);
var adjusted = new OffsetDateTime(
    new LocalDateTime(desiredLocalDate.Year, desiredLocalDate.Month, desiredLocalDate.Day, parsed.Hour, parsed.Minute, parsed.Second, parsed.Millisecond),
    parsed.Offset);
var localTime = adjusted.LocalDateTime;

I guess I'm wondering whether I'm overlooking a better way to do this.

like image 401
Kent Boogaart Avatar asked Oct 18 '22 11:10

Kent Boogaart


1 Answers

Update: this will now be in Noda Time 2.3.


No, there isn't anything representing this in Noda Time. It's a pretty odd kind of value, as in at least many time zones, the offset will vary over the year. I understand that sometimes we need to work with what we've got though.

I'd probably keep it as two fields: an Offset, and a LocalTime. You can then build an OffsetDateTime once you have a LocalDate. You could obtain those two via an OffsetDateTime as you're doing already, but I'd suggest splitting it into the two values as soon as possible, to avoid any hint that there's a useful date in there.

If you want to keep your existing code structure, you can at least make it much simpler:

// The date for this OffsetDateTime will be 1/1/2000
// Note: the pattern can be created once and reused; it's thread-safe.
var parsed = OffsetDateTimePattern.CreateWithInvariantCulture("HH:mm:sso<G>")
    .Parse(input).Value;
var desiredLocalDate = new LocalDate(2017, 06, 13);
var adjusted = desiredLocalDate.At(parsed.TimeOfDay).WithOffset(parsed.Offset);
var localTime = adjusted.LocalDateTime;

Note that localTime here will always be equivalent to desiredLocalDate.At(parsed.TimeOfDay) - it's not like the offset is "added" to it.

like image 125
Jon Skeet Avatar answered Oct 21 '22 03:10

Jon Skeet