0

If I have a string like "2020-12-15T12:10:00.202" how can I parse this into NodaTime.LocalDateTime directly, rather than doing something like:

LocalDateTime.FromDateTime(DateTime.Parse("2020-12-15T12:10:00.202"))

And similarly for the other NodaTime types like LocalDate, Instant etc.

1 Answer 1

3

You use a LocalDateTimePattern. For example:

// Note: patterns are thread-safe and immutable. Various patterns are provided as
// static properties on the relevant pattern class. If you can't use one of those
// patterns, it's often useful to store the pattern in a static readonly field.
var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd'T'HH:mm:ss.fff");

// There's no Parse/TryParse separation - there's just Parse, which returns a
// ParseResult<T> that indicates success/failure.
ParseResult<LocalDateTime> parsed = pattern.Parse("2020-12-15T12:10:00.202");

// Note: if you're okay with invalid input causing an exception, just use
// parsed.Value directly - it will throw a descriptive exception if parsing failed.
if (parsed.Success)
{
    LocalDateTime result = parsed.Value;
    // Use the result here
}
else
{
    // Handle the failure
}

For more details about text handling, see the section in the user guide.

Note that there's no direct equivalent of DateTime.Parse itself, that tries multiple different date/time formats automatically - but you can use a CompositePatternBuilder<T> to try multiple patterns when parsing if you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.