If you want to change formatting styles provided by DateFormat
, you can use SimpleDateFormat
class. The SimpleDateFormat
class is locale-sensitive.
If you instantiate SimpleDateFormat
without a Locale
parameter, it will format the date and time according to the default Locale
. Both the pattern
and the Locale
determine the format. For the same pattern, SimpleDateFormat
may format a date and time differently if the Locale
varies.
package org.kodejava.text;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class SimpleDateFormatChangeLocalePattern {
public static void main(String[] args) {
String pattern = "dd-MMM-yyyy";
Date today = new Date();
// Gets a formatted date according to the given pattern.
// Here only the pattern is passed as argument of the
// SimpleDateFormat constructor, so it will format the
// date according to the default Locale.
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String local = sdf.format(today);
System.out.println("Date in default locale: " + local);
Locale[] locales = {
Locale.CANADA,
Locale.FRANCE,
Locale.GERMANY,
Locale.US,
Locale.JAPAN
};
for (Locale locale : locales) {
// Format a date according to the given pattern for each locale.
sdf = new SimpleDateFormat(pattern, locale);
String after = sdf.format(today);
System.out.println(locale.getDisplayCountry() + " | format: " + after);
}
}
}
Here are the variety of output produces when formatting a date in the same date pattern but varies in Locale
Date in default locale: 19-Oct-2021
Canada | format: 19-Oct.-2021
France | format: 19-oct.-2021
Germany | format: 19-Okt.-2021
United States | format: 19-Oct-2021
Japan | format: 19-10月-2021
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024