Home > Back-end >  How to get locale specific Date/Time patterns in Java in a future-proof way
How to get locale specific Date/Time patterns in Java in a future-proof way

Time:08-12

TL;DR: How do I get from having locale and SHORT/MEDIUM/LONG etc to the pattern String to parse a date.

Full version:

Accessing the pattern of a locale-specific date format seems to be problem not well covered in Java.

This is in the context of

I'm bringing this question back due to the JDK-specificity of the first, and the implementation-specific-ness of the second question, this time to be answered in a non-version-specific way, long after 2017 (the date of the first question):

Use case:

On the user interface, show the date format that a date will be parsed with, when entered: E.g. For Locale.US display start date (M/d/yy), for Locale.GERMANY show Startdatum (dd.MM.yy) next to an input (or, in HTML, as a placeholder).

This would be trivial to achieve - as long as it still works - with

DateFormat usFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
DateFormat deFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMANY);
System.out.println(((SimpleDateFormat) usFormat).toPattern()); // M/d/yy
System.out.println(((SimpleDateFormat) deFormat).toPattern()); // dd.MM.yy

but this code involves the old API and an implementation specific typecast - both are assumptions that I'm not too confident using.

Maintaining my own library of locale-specific patterns seems even less advisable, but with the DateTime API not granting any access to its internal patterns (they must be there):

Is there a way to solve this problem in a future-proof way?

Due to the linked questions above, this likely involves a specific minimal Java version, and that's fine. I'm currently still bound to be 8 and 11 compatible, but this could either push the version further, or provide an alternative future proof implementation for instances running under newer Java versions.

CodePudding user response:

You can use the DateTimeFormatterBuilder to get the format string:

String usFormat = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.SHORT, null, IsoChronology.INSTANCE, Locale.US);
String deFormat = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.SHORT, null, IsoChronology.INSTANCE, Locale.GERMANY);
System.out.println(usFormat); // M/d/yy
System.out.println(deFormat); // dd.MM.yy
  • Related