Localized Formatting with ofLocalizedDate and ofLocalizedTime
You'll learn how to create date and time formatters that automatically adapt to different countries and cultures using FormatStyle.
Why Localization Matters
When your application serves users worldwide, displaying dates as "12/25/2023" (US style) versus "25/12/2023" (European style) matters. Instead of manually building patterns for each locale, Java provides locale-sensitive formatters that handle these differences automatically.
The ofLocalizedDate and ofLocalizedTime Methods
These static methods on DateTimeFormatter create formatters that respect the user's locale (country/language settings):
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
FormatStyle Options
Java provides four verbosity levels through the FormatStyle enum:
- FULL: Complete, formal representation (e.g., "Monday, December 25, 2023")
- LONG: More detailed (e.g., "December 25, 2023")
- MEDIUM: Balanced detail (e.g., "Dec 25, 2023")
- SHORT: Compact (e.g., "12/25/23")
Using Localized Formatters
LocalDate date = LocalDate.of(2023, 12, 25);
Locale usLocale = Locale.US;
Locale germanLocale = Locale.GERMANY;
DateTimeFormatter shortFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(usLocale);
System.out.println(date.format(shortFormatter)); // 12/25/23
shortFormatter = shortFormatter.withLocale(germanLocale);
System.out.println(date.format(shortFormatter)); // 25.12.23
Similarly, ofLocalizedTime formats time values according to locale conventions (12-hour vs 24-hour clocks, AM/PM placement).
Think of It Like This
Localized formatters are like having a translator who knows not just the language, but also the cultural conventions—automatically choosing whether to write the day or month first.
Key Takeaway: Use ofLocalizedDate and ofLocalizedTime with FormatStyle enums (FULL, LONG, MEDIUM, SHORT) to create internationalization-friendly formatters that adapt date and time displays to your users' cultural expectations.