I have code and a test-case in a legacy application, which can be summarized as follows:
@Test
public void testParseDate() throws ParseException {
String toParse = "Mo Aug 18 11:25:26 MESZ +0200 2014";
String pattern = "EEE MMM dd HH:mm:ss z Z yyyy";
DateFormat dateFormatter = new SimpleDateFormat(pattern, Locale.GERMANY);
Date date = dateFormatter.parse(toParse);
//skipped assumptions
}
This test passes in Java 8 and below. However with Java 10 upwards this leads to a java.text.ParseException: Unparseable date: "Mo Aug 18 11:25:26 MESZ +0200 2014"
.
For the record:
Besides de_DE
, the exception is also thrown for the locales
de_CH
, de_AT
, de_LU
.
I am aware of the fact, that Date formatting was changed with JDK 9 (JEP 252). However, I consider this to be a disruptive change breaking backwards compatibility. Excerpted:
In JDK 9, the Unicode Consortium's Common Locale Data Repository (CLDR) data is enabled as the default locale data, so that you can use standard locale data without any further action.
In JDK 8, although CLDR locale data is bundled with the JRE, it isn’t enabled by default.
Code that uses locale-sensitive services such as date, time, and number formatting may produce different results with the CLDR locale data.
Adding a .
for the day of the week (Mo.
) compensates for this and test would pass. However, this is not a real solution for old data (in serialized form such as XML).
Checking this stackoverflow post, it seems that the behaviour is intentional for the German locale and can be mitigated by specifying java.locale.providers
with COMPAT
mode. However, I do not like the idea to rely on some system property value for two reasons as it might:
- change in the next releases of the JDK.
- be forgotten in different environments.
My question is:
- How can I maintain backwards compatibility of legacy code with this particular date pattern, without re-writing / modifying existing serialized data or adding / changing system properties (like
java.locale.providers
), which may be forgotten in different environments (application servers, standalone jars, ...) ?