How to localize date format in Java

1 Answer

0 votes
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;

// Localized Date Formatting

public class LocalizedDateExample {
    public static void main(String[] args) {

        LocalDateTime now = LocalDateTime.now();

        // 1. Use system default locale
        Locale systemLocale = Locale.getDefault();
        System.out.println("--- Using system locale: " + systemLocale + " ---");

        System.out.println("Short date : " +
                now.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).withLocale(systemLocale)));

        System.out.println("Long date  : " +
                now.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).withLocale(systemLocale)));

        System.out.println("Time       : " +
                now.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM).withLocale(systemLocale)));

        System.out.println("Weekday    : " +
                now.format(DateTimeFormatter.ofPattern("EEEE", systemLocale)));

        System.out.println("Month name : " +
                now.format(DateTimeFormatter.ofPattern("MMMM", systemLocale)));


        // 2. Force a specific locale (example: French)
        Locale french = Locale.FRANCE;
        System.out.println("\n--- Using French locale ---");

        System.out.println("Short date : " +
                now.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).withLocale(french)));

        System.out.println("Long date  : " +
                now.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).withLocale(french)));

        System.out.println("Weekday    : " +
                now.format(DateTimeFormatter.ofPattern("EEEE", french)));

        System.out.println("Month name : " +
                now.format(DateTimeFormatter.ofPattern("MMMM", french)));
    }
}



/*
run:

--- Using system locale: en_US ---
Short date : 4/19/26
Long date  : Sunday, April 19, 2026
Time       : 8:41:00?AM
Weekday    : Sunday
Month name : April

--- Using French locale ---
Short date : 19/04/2026
Long date  : dimanche 19 avril 2026
Weekday    : dimanche
Month name : avril

*/

 



answered 15 hours ago by avibootz
...