SimpleDateFormat Illegal pattern character error with localized pattern
Unfortunately the documentation of how to handle localized patterns is horrible. So I studied the source code and made my own investigations. Result:
The constructor of SimpleDateFormat
accepting a pattern string only refers to the unlocalized pattern characters whose definition is documented as given in the javadoc header of class SimpleDateFormat
. These unlocalized pattern characters are also defined as constant in DateTimeFormatSymbols
:
/**
* Unlocalized date-time pattern characters. For example: 'y', 'd', etc.
* All locales use the same these unlocalized pattern characters.
*/
static final String patternChars = "GyMdkHmsSEDFwWahKzZYuXL";
Three steps are necessary in order to use localized patterns (like "tt.MM.uuuu" what you believe to be German - but is NOT German, it should rather be "TT.MM.JJJJ" - example for wrong JDK resources):
- Define the localized pattern characters via
DateFormatSymbols.setLocalPatternChars(...)
. - Use the customized date-format-symbols on your
SimpleDateFormat
-object. - Apply the localized date-time-pattern via
SimpleDateFormat.applyLocalizedPattern(...)
Then the localized pattern will be translated to the internal and official pattern character definition.
Example of usage (using the correct German pattern TT.MM.JJJJ):
SimpleDateFormat sdf = new SimpleDateFormat(); // uses default locale (here for Germany)
System.out.println(sdf.toPattern()); // dd.MM.yy HH:mm
System.out.println(sdf.toLocalizedPattern()); // tt.MM.uu HH:mm
DateFormatSymbols dfs = DateFormatSymbols.getInstance(Locale.GERMANY);
dfs.setLocalPatternChars("GJMTkHmsSEDFwWahKzZYuXL");
sdf.setDateFormatSymbols(dfs);
sdf.applyLocalizedPattern("TT.MM.JJJJ");
System.out.println(sdf.toPattern()); // dd.MM.yyyy
System.out.println(sdf.toLocalizedPattern()); // TT.MM.JJJJ
System.out.println(sdf.format(new Date())); // 20.06.2016
Side note: I have changed the appropriate pattern chars y and d to J and T in the string "GyMdkHmsSEDFwWahKzZYuXL" to make a localized definition.
Unfortunately the JDK resources are obviously not reliable so my personal view is that the whole feature can only be used in an awkward way and is not very useful in practice.