强制从java.time中的`DateTimeFormatter.ofLocalized …`生成的本地化字符串中的4位数年份

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类。 但我找不到任何改变一年的长度的function。 我也仔细阅读了Java 9源代码 ,但是不能很好地解释代码以找到答案。

这个问题类似于:

  • 在java的simpledateformat中强制使用4位数年份
  • Jodatime:如何打印4位数年份?

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

没有内置的方法可以满足您的需求。 但是,您可以应用以下解决方法:

 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