c# - 如何使用 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));
我错过了什么?
解决方案
首先,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"
推荐阅读
- angular - 我无法正确共享我的 Observable 流并且我的 http 请求调用了两次
- google-apps-script - 用于 Gmail 的 Google 应用程序脚本 - 收件箱中损坏的电子邮件
- java - RAD studio 10.3.3 无法创建 java 虚拟机
- python - 删除已排序 DataFrame 中的相邻重复项
- java - 将openjdk编译到Android
- java - 如何从“\.”中逃脱 使用 Java 和 Selenium
- php - 表单提交后无法回显变量
- coq - 具有复杂类型的复杂函数的相等性
- javascript - 仅使用 JavaScript 按类名随机化多个 ul 标记
- python - 如何检查列表是否包含具有相同键的dict元素