System.setProperty("java.locale.providers", "COMPAT,CLDR");
DateFormat dateFormat
= DateFormat.getDateInstance(DateFormat.SHORT, new Locale("sv", "SE"));
System.out.println(((SimpleDateFormat) dateFormat).toPattern());
Running on my jdk-9.0.4 this prints
yyyy-MM-dd
You may want to set the property with -D
on the command line instead, it shouldn’t make any difference.
In Java 9 the Common Locale Data Repository (CLDR) from the Unicode Consortium is used as the default source of locale data, which wasn’t the case in earlier Java versions. Setting the system property as above enables the Java 8 behaviour. As nullpointer said in a comment, you can read a bit more here: Use CLDR Locale Data by Default.
Basil Bourque is correct in his comment, it is customary to use lowercase abbrevation for language, so you should probably specify sv
to make sure you don’t confuse your reader.
One might also wonder whether it makes any difference whether there’s one y
or four in the pattern. The way I read the SimpleDateFormat
documentation, one y
will interpret a 2-digit year according to the 80-20 rule: it’s within the last 80 years or within the next 20. yyyy
will interpret a 2-digit year as a year in the first century AD. Assuming your years are in the 4-digit range (1000 through 9999), I wouldn’t expect it to be a problem, though.
If this was only for Swedish locale, the modern version of the code would give the same result:
DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT, null, IsoChronology.INSTANCE, new Locale("SV", "SE")));
However, for a number of locales (en-CY
, Cyprus English, for example) the result differs from DateFormat
to DateTimeFormatter
, so if your goal was maximal backward compatibility, stick with the outmoded DateFormat
class.
"yyyy-MM-dd"
, just use the string"yyyy-MM-dd"
. If you ask a factory for the pattern for a locale and style, you accept that this is a moving target. I doubt that Sweden is willing to nail down their date format just for the sake of some legacy Java code… – LaminaSimpleDateFormat
? I can understand if you don’t want to remove it from your legacy code right now, but for the task at hand, useDateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.SHORT, null, IsoChronology.INSTANCE, new Locale("SV", "SE"))
(this doesn’t solve your problem, though, it too behaves differently in Java 8 and 9). – Olid