java.time
The legacy date-time API (java.util
date-time types and their formatting API, SimpleDateFormat
) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time
, the modern date-time API*.
You can use DateTimeFormatter.ofLocalizedDateTime
to obtain a locale-specific date format for the ISO chronology.
Demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtfLocalized = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT);
// Test
LocalDateTime date = LocalDateTime.now();
System.out.println(dtfLocalized.withLocale(Locale.US).format(date));
System.out.println(dtfLocalized.withLocale(Locale.UK).format(date));
System.out.println(dtfLocalized.withLocale(Locale.CHINESE).format(date));
System.out.println(dtfLocalized.withLocale(Locale.GERMAN).format(date));
System.out.println(dtfLocalized.withLocale(Locale.forLanguageTag("tr")).format(date));
System.out.println(dtfLocalized.withLocale(Locale.getDefault()).format(date));
}
}
Output:
5/8/21, 10:49 PM
08/05/2021, 22:49
2021/5/8 δΈε10:49
08.05.21, 22:49
8.05.2021 22:49
08/05/2021, 22:49
Learn more about the 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.