【发布时间】: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