I often create SimpleDateFormat with a patterns like HH:mm:ss
or yyyy-MM-dd
to output dates in a locale independant way. Since there is a also constructor taking an additional locale parameter I'm wondering if there are cases where such a format can be locale dependant, or if I should always specify Locale.ENGLISH or Locale.GERMANY. Lets assume that the timezone is set explicitly.
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.
Class SimpleDateFormat. Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.
The steps are exactly the same but instead of using SimpleDateFormat and Date class, we'll use the DateTimeFormatter and LocalDateTime class. The DateTimeFormatter class is used to format and parse the date in Java 8 and LocalDateTime represents a date with time in the local timezone.
Just found the getAvailableLocales
static method on Locale, and it turns out that all the fields of a calendar can be locale dependent:
public static void main(String[] args) {
String pattern = "yyyy-MM-dd HH:mm:ss";
Date date = new Date();
String defaultFmt = new SimpleDateFormat(pattern).format(date);
for (Locale locale : Locale.getAvailableLocales()) {
String localeFmt = new SimpleDateFormat(pattern, locale).format(date);
if (!localeFmt.equals(defaultFmt)) {
System.out.println(locale + " " + localeFmt);
}
}
}
On my system (in germany running an english version of ubuntu) this outputs the following list, lets hope the unicode character come through intact:
ja_JP_JP 23-03-03 16:53:09
hi_IN २०११-०३-०३ १६:५३:०९
th_TH 2554-03-03 16:53:09
th_TH_TH ๒๕๕๔-๐๓-๐๓ ๑๖:๕๓:๐๙
So Japan and Thailand use a different epoch but are otherwise based on the gregorian calendar, which explains why month and day are the same.
Other locales also use different scripts for writing numbers, for example Hindi spoken in India and a variant of Thai in Thailand.
To answer the question, the locale should alway be specified to a known value when a locale independant String is needed.
Edit: Java 1.6 added a constant Locale.ROOT to specify a language/country neutral locale. This would be preferred to specifying the English locale for output targeted at a computer.
The root locale is the locale whose language, country, and variant are empty ("") strings. This is regarded as the base locale of all locales, and is used as the language/country neutral locale for the locale sensitive operations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With