Dan Liebster
Dan Liebster

Reputation: 455

How do you parse a date and time string with offset using NodaTime?

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:

How do I parse this with NodaTime to get an

Upvotes: 4

Views: 1571

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241633

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

Upvotes: 5

Related Questions