Reputation: 455
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:
"2012/08/30 17:45:00"
"yyyy/MM/dd HH:mm:ss"
-5
How do I parse this with NodaTime to get an
OffsetDateTime
?Instant
?Upvotes: 4
Views: 1571
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