How to parse a date from a string
Short answer
LocalDate.parse() understands an ISO string (2026-03-08) with no extra setup:
void main() {
LocalDate date = LocalDate.parse("2026-03-08");
IO.println(date);
IO.println(date.getDayOfWeek());
}Output:
2026-03-08
SUNDAYA custom format
For other formats pass a DateTimeFormatter with a pattern:
void main() {
var formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
LocalDate date = LocalDate.parse("08.03.2026", formatter);
IO.println(date);
}Output:
2026-03-08Date and time
LocalDateTime.parse() parses a string with a time:
void main() {
var formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
LocalDateTime meeting = LocalDateTime.parse("15/04/2026 09:30", formatter);
IO.println(meeting);
IO.println(meeting.plusHours(2).toLocalTime());
}Output:
2026-04-15T09:30
11:30Month as a word
If the string contains a month name, specify the language:
void main() {
var formatter = DateTimeFormatter.ofPattern("d MMMM yyyy", Locale.ENGLISH);
IO.println(LocalDate.parse("8 March 2026", formatter));
}Output:
2026-03-08Common mistake
Not handling an invalid string. parse() throws a DateTimeParseException:
void main() {
LocalDate.parse("2026-02-30");
}Output:
Exception in thread "main" java.time.format.DateTimeParseException: Text '2026-02-30' could not be parsed: Invalid date 'FEBRUARY 30'
Caused by: java.time.DateTimeException: Invalid date 'FEBRUARY 30'Functions used in this recipe
- LocalDate.parse() — Parses a date from a string — in ISO format (2025-03-14) or with a pattern.
- DateTimeFormatter.ofPattern() — Creates a formatter for printing and parsing dates with a pattern such as dd.MM.yyyy.