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:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// A sample date string
String strDate = "20210630";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("uuuuMMdd", Locale.ENGLISH);
LocalDate date = LocalDate.parse(strDate, dtfInput);
System.out.println(date.format(getShortDateFormatterForLocale(Locale.getDefault())));
System.out.println(date.format(getShortDateFormatterForLocale(Locale.GERMANY)));
System.out.println(date.format(getShortDateFormatterForLocale(Locale.US)));
}
static DateTimeFormatter getShortDateFormatterForLocale(Locale locale) {
return DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).localizedBy(locale);
}
}
Output on my system in the UK:
30/06/2021
30.06.21
6/30/21
ONLINE DEMO
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.