According the javadocs I can create a SimpleDateFormat
that is locale aware.
But trying out the following code:
Locale [] locales = {
Locale.GERMANY,
Locale.CANADA_FRENCH,
Locale.CHINA,
Locale.ITALIAN,
Locale.JAPANESE,
Locale.ENGLISH
};
try {
for(Locale locale : locales) {
final SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", locale);
System.out.println(myFormat.parse("2017-04-01 12:00:01"));
}
} catch (ParseException e) {
e.printStackTrace();
}
I see in the output:
Sat Apr 01 12:00:01 CEST 2017
Sat Apr 01 12:00:01 CEST 2017
Sat Apr 01 12:00:01 CEST 2017
Sat Apr 01 12:00:01 CEST 2017
Sat Apr 01 12:00:01 CEST 2017
Sat Apr 01 12:00:01 CEST 2017
So why are all the same date format regardless of the locale?
Update after comment:
for(Locale locale : locales) {
System.out.println("Locale " + locale);
final SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", locale);
System.out.println(myFormat.parse("2017-04-01 12:00:01"));
System.out.println(myFormat.format(myFormat.parse("2017-04-01 12:00:01")));
System.out.println("-----------");
}
The above snippet prints:
-----------
Locale zh_CN
Sat Apr 01 12:00:01 CEST 2017
2017-04-01 12:00:01
-----------
Locale it
Sat Apr 01 12:00:01 CEST 2017
2017-04-01 12:00:01
-----------
Locale ja
Sat Apr 01 12:00:01 CEST 2017
2017-04-01 12:00:01
-----------
Locale en
Sat Apr 01 12:00:01 CEST 2017
2017-04-01 12:00:01
-----------
Update 2:
The following code takes locale into account:
final SimpleDateFormat myFormat1 = new SimpleDateFormat("dd-MMM-yyyy");
final SimpleDateFormat myFormat = new SimpleDateFormat("dd-MMM-yyyy", locale);
Date date = myFormat1.parse("05-Apr-2017");
String out = myFormat.format(date);
System.out.println(out);
System.out.println("-----------");
Output is:
Locale de_DE
05-Apr-2017
-----------
Locale fr_CA
05-avr.-2017
-----------
Locale zh_CN
05-四月-2017
-----------
Locale it
05-apr-2017
-----------
Locale ja
05-4-2017
-----------
Locale en
05-Apr-2017
-----------
But how come this works as (I) expected? Why does
yyyy-MM-dd HH:mm:ss
and dd-MMM-yyyy
behave so differently?