Question

I am trying to learn how to use NodaTime within my application, but cannot find very many examples of how to do certain things with this library.

Given:

  • date/time text of "2012/08/30 17:45:00"
  • the format string is "yyyy/MM/dd HH:mm:ss"
  • the date/time offset from UTC is -5

How do I parse this with NodaTime to get an

  • OffsetDateTime?
  • Instant?
Was it helpful?

Solution

Using pure NodaTime code, there is not currently a direct parser for an OffsetDateTime. See the documented limitations. However, you can construct one by parsing a LocalDateTime and an Offset separately:

var ldt = LocalDateTimePattern.CreateWithInvariantCulture("yyyy/MM/dd HH:mm:ss")
                              .Parse("2012/08/30 17:45:00")
                              .Value;

var o = OffsetPattern.GeneralInvariantPattern
                     .Parse("-05")
                     .Value;

var odt = new OffsetDateTime(ldt, o);

There is a similar parser for Instant, but it requires a UTC time - not an offset.

You could also just use the text parsing for DateTimeOffset in the BCL, and then do:

var odt = OffsetDateTime.FromDateTimeOffset(dto);

Either way, once you have an OffsetDateTime, it is convertible to an Instant:

var instant = odt.ToInstant();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top