javalocalizationjava-time2-digit-year

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:

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


Solution

  • 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