Search for the country name using the Locale
object while navigating DateFormat.getAvailableLocales()
and break the loop once you've found it.
import java.text.DateFormat;
import java.time.LocalDate;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.FormatStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Locale localePk = null;
for (Locale locale : DateFormat.getAvailableLocales()) {
if (locale.getDisplayCountry().equals("Pakistan")) {
localePk = locale;
break;
}
}
if (localePk != null) {
String datePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.SHORT, null,
IsoChronology.INSTANCE, localePk);
System.out.println(LocalDate.now().format(DateTimeFormatter.ofPattern(datePattern, localePk)));
}
}
}
Output:
10/10/2020
Note that DateTimeFormatterBuilder
is part of the modern date-time API.
If you are doing it for your 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.
java.util
date-time classes are outdated and error-prone and so is their formatting API, DateFormat
. However, if you are still looking for a solution using these legacy APIs, given below is one:
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Locale localePk = null;
for (Locale locale : DateFormat.getAvailableLocales()) {
if (locale.getDisplayCountry().equals("Pakistan")) {
localePk = locale;
break;
}
}
if (localePk != null) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, localePk);
System.out.println(df.format(new Date()));
}
}
}
Output:
10/10/2020