How to format a date
Short answer
Create a DateTimeFormatter with a pattern and pass it to format():
void main() {
var date = LocalDate.of(2026, 3, 8);
var formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
IO.println(date.format(formatter));
}Output:
08.03.2026Pattern letters
yyyy is the year, MM the month as a number, MMM/MMMM the month name, dd the day, HH hours (0–23), mm minutes, ss seconds, EEEE the day of the week:
void main() {
var dateTime = LocalDateTime.of(2026, 3, 8, 14, 5, 9);
IO.println(dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
IO.println(dateTime.format(DateTimeFormatter.ofPattern("EEEE, d MMMM yyyy", Locale.ENGLISH)));
}Output:
2026-03-08 14:05:09
Sunday, 8 March 2026In another language
Month and day names depend on the locale:
void main() {
var date = LocalDate.of(2026, 3, 8);
IO.println(date.format(DateTimeFormatter.ofPattern("d MMMM yyyy", Locale.GERMAN)));
IO.println(date.format(DateTimeFormatter.ofPattern("d MMMM yyyy", Locale.of("ru"))));
}Output:
8 März 2026
8 марта 2026Built-in formats
ofLocalizedDate() picks the format used in a country:
void main() {
var date = LocalDate.of(2026, 3, 8);
var style = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
IO.println(date.format(style.withLocale(Locale.US)));
IO.println(date.format(style.withLocale(Locale.UK)));
IO.println(date.format(DateTimeFormatter.ISO_DATE));
}Output:
Mar 8, 2026
8 Mar 2026
2026-03-08Common mistake
Mixing up letter case. MM is the month, mm minutes; YYYY is the "week-based year", which can differ from the regular year at the end of December:
void main() {
var dateTime = LocalDateTime.of(2025, 12, 29, 10, 45);
IO.println(dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
IO.println(dateTime.format(DateTimeFormatter.ofPattern("YYYY-mm-dd", Locale.UK)));
}Output:
2025-12-29
2026-45-29In the second line both the year is wrong and minutes appear instead of the month.
Functions used in this recipe
- DateTimeFormatter.ofPattern() — Creates a formatter for printing and parsing dates with a pattern such as dd.MM.yyyy.