首页 > 解决方案 > 如何使用 NodaTime 对 Culture 的 ShortDatePattern 进行字符串格式化?

问题描述

使用 C# DateTime 和 Culture 我可以格式化为字符串:

DateTime exampleDate = DateTime.Now;
CultureInfo culture = new CultureInfo("fr-FR");
String datetimeFormat = exampleDate.ToString(culture.DateTimeFormat.ShortDatePattern));

如何使用 NodaTime 实现相同的目标?我已经尝试过以下组合(不编译 - ToString 需要两个带有 NodaTimef 的参数):

DateTimeZone timeZone = DateTimeZoneProviders.Tzdb["fr-FR"];
ZonedDateTime nowZonedDateTime = new ZonedDateTime(Instant.FromDateTimeUtc(DateTime.Now.ToUniversalTime()), timeZone);
String nodaFormat = nowZonedDateTime.LocalDateTime.ToString(culture.DateTimeFormat.ShortDatePattern));

我还尝试了围绕文档的组合,这表明我需要使用“d”来格式化为短日期(这会引发异常):

String nodaFormat = nowZonedDateTime.LocalDateTime.ToString("d", culture));

我错过了什么?

标签: c#nodatime

解决方案


首先,fr-FR在 TZDB 中没有 ID 为的时区,您的意思是Europe/Paris

其次,ToString实际上接受 2 个参数 - 一个模式字符串和一个IFormatProvider,它可以是你的CultureInfo. 所以你就快到了 - 你只需要传入culture作为第二个参数:

CultureInfo culture = new CultureInfo("fr-FR");
DateTimeZone timeZone = DateTimeZoneProviders.Tzdb["Europe/Paris"];
ZonedDateTime nowZonedDateTime = new ZonedDateTime(Instant.FromDateTimeUtc(DateTime.Now.ToUniversalTime()), timeZone);
String nodaFormat = nowZonedDateTime.LocalDateTime.ToString(culture.DateTimeFormat.ShortDatePattern, culture);
// nodaFormat would be "27/12/2019"

推荐阅读