SimpleDateFormat toPattern behaves differently in java 9

前端 未结 1 865
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-13 05:43
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, new Locale(\"SV\", \"SE\"));
((SimpleDateFormat) dateFormat).toPattern();

In J

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-13 06:09

        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.

    0 讨论(0)
提交回复
热议问题