Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 560
Basil Bourque Avatar asked Nov 25 '16 23:11

Basil Bourque


1 Answers

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
like image 187
Meno Hochschild Avatar answered Nov 13 '22 14:11

Meno Hochschild