We create J2SE application that has to format the date and time according to custom the country from which users come from. I want to ask how to solve this thing in Java? Probably I'll use SimpleDateFormat, but I wonder if it is possible to get format string in somehow simpler way than to have all format strings for each country separately.
2 Answers
DateFormat
already allows you to do this - just use DateTimeFormat.getDateTimeInstance(dateStyle, timeStyle, locale)
or something similar, depending on your needs.

- 1,421,763
- 867
- 9,128
- 9,194
java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time
, the modern Date-Time API:
Use DateTimeFormatter.#ofLocalizedDate
to get a locale specific date format for the ISO chronology.
Demo:
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtfDateFull = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)
.localizedBy(new Locale("cs", "CZ"));
DateTimeFormatter dtfDateMedium = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
.localizedBy(new Locale("cs", "CZ"));
DateTimeFormatter dtfDateShort = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
.localizedBy(new Locale("cs", "CZ"));
LocalDate date = LocalDate.now(ZoneId.of("Europe/Prague"));
System.out.println(date.format(dtfDateFull));
System.out.println(date.format(dtfDateMedium));
System.out.println(date.format(dtfDateShort));
}
}
Output from a sample run:
neděle 18. července 2021
18. 7. 2021
18.07.21
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

- 71,965
- 6
- 74
- 110