Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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
SUNDAY

A 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-08

Date 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:30

Month 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-08

Common 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'

For user input, wrap the parsing in try/catch.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.