【问题标题】:Force 4-digit-year in localized strings generated from `DateTimeFormatter.ofLocalized…` in java.time在 java.time 中从 `DateTimeFormatter.ofLocalized...` 生成的本地化字符串中强制使用 4 位数年份
【发布时间】:2017-04-10 08:32:15
【问题描述】:

java.time 中的DateTimeFormatter 类提供了三个ofLocalized… 方法来生成字符串来表示包含年份的值。例如,ofLocalizedDate。

Locale l = Locale.US ; 
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( l );
LocalDate today = LocalDate.now( ZoneId.of( "America/Chicago" ) );
String output = today.format( f );

对于我所看到的语言环境,在较短的FormatStyle 样式中,年份只有两位数。

如何让 java.time 本地化强制年份为四位数而不是两位?

我怀疑答案在于DateTimeFormatterBuilder 类。但我找不到任何改变年份长度的功能。我还仔细阅读了Java 9 source code,但无法很好地挖掘该代码以找到答案。

这个问题类似于:

...但是这些问题针对的是现在被 java.time 类取代的旧日期时间框架。

【问题讨论】:

  • 在您的示例中,年份有四位数字(FormatStyle.FULL、FormatStyle.LONG 或 FormatStyle.MEDIUM)。你到底在问什么?
  • @assylias 我的问题文本是指较短的格式。我修复了示例代码以匹配。

标签: java localization java-time 2-digit-year


【解决方案1】:

没有你想要的内置方法。但是,您可以应用以下解决方法:

Locale locale = Locale.ENGLISH;
String shortPattern =
    DateTimeFormatterBuilder.getLocalizedDateTimePattern(
        FormatStyle.SHORT,
        null,
        IsoChronology.INSTANCE,
        locale
    );
System.out.println(shortPattern); // M/d/yy
if (shortPattern.contains("yy") && !shortPattern.contains("yyy")) {
    shortPattern = shortPattern.replace("yy", "yyyy");
}
System.out.println(shortPattern); // M/d/yyyy

DateTimeFormatter shortStyleFormatter = DateTimeFormatter.ofPattern(shortPattern, locale);
LocalDate today = LocalDate.now(ZoneId.of("America/Chicago"));
String output = today.format(shortStyleFormatter);
System.out.println(output); // 11/29/2016

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2021-10-15
    相关资源
    最近更新 更多