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

元气小坏坏 提交于 2019-11-26 22:06:16

问题


The 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 );

For the locales I have seen, the year is only two digits in the shorter FormatStyle styles.

How to let java.time localize yet force the years to be four digits rather than two?

I suspect the Answer lies in DateTimeFormatterBuilder class. But I cannot find any feature alter the length of year. I also perused the Java 9 source code, but cannot spelunk that code well enough to find an answer.

This Question is similar to:

  • forcing 4 digits year in java's simpledateformat
  • Jodatime: how to print 4-digit year?

…but those Questions are aimed at older date-time frameworks now supplanted by the java.time classes.


回答1:


There is no built-in method for what you want. However, you could apply following workaround:

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


来源:https://stackoverflow.com/questions/40813476/force-4-digit-year-in-localized-strings-generated-from-datetimeformatter-ofloca

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!