相当于NodaTime中的DateTime.Parse?

Equivalent to DateTime.Parse in NodaTime?

如果我有一个像“2020-12-15T12:10:00.202”这样的字符串,我该如何将其直接解析为 NodaTime.LocalDateTime,而不是像这样:

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

其他 NodaTime 类型也类似,如 LocalDateInstant

您使用了 LocalDateTimePattern。例如:

// 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
}

有关文本处理的更多详细信息,请参阅 section in the user guide

请注意,没有 direct 等同于 DateTime.Parse 本身,它会自动尝试多种不同的 date/time 格式 - 但您可以使用 CompositePatternBuilder<T> 如果需要,可以在解析时尝试多种模式。