如何使用 NodaTime 将字符串格式与 Culture 的 ShortDatePattern 一起使用?
How do I use NodaTime to string format with a Culture's ShortDatePattern?
使用 C# 日期时间和文化,我可以格式化为字符串:
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));
我错过了什么?
首先,TZDB中没有ID为fr-FR
的时区,你是说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"
使用 C# 日期时间和文化,我可以格式化为字符串:
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));
我错过了什么?
首先,TZDB中没有ID为fr-FR
的时区,你是说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"