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

Force 4-digit-year in localized strings generated from `DateTimeFormatter.ofLocalized…` in java.time

DateTimeFormatter class in java.time offers three ofLocalized… methods for generating strings to represent values that include a year. For example, 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 class. But I cannot find any feature alter the length of year. I also perused the Java 9 source code 中,但无法很好地探索该代码以找到答案。

这个问题类似于:

…但这些问题针对的是现在已被 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