Search code examples
javadatetimejava-timeisolocaldatetime

How to parse an ISO date with LocalDateTime.parse(...)


I want to parse a date string like 2011-11-30 like this:

LocalDateTime.parse("2011-11-30", DateTimeFormatter.ISO_LOCAL_DATE)

But I get the following exception:

java.time.format.DateTimeParseException: Text '2011-11-30' could not be parsed:
Unable to obtain LocalDateTime from TemporalAccessor

If I pass a date and time string everything works as expected:

LocalDateTime.parse("2011-11-30T23:59:59", DateTimeFormatter.ISO_LOCAL_DATE_TIME)

How can I parse a date like 2011-11-30 to a LocalDateTime (with a default time)?


Solution

  • As @JB Nizet suggested, the following works

    LocalDate localDate = LocalDate.parse("2011-11-30", DateTimeFormatter.ISO_LOCAL_DATE);
    LocalDateTime localDateTime = localDate.atTime(23, 59, 59);
    System.out.println(localDateTime); // 2011-11-30T23:59:59
    

    How can I parse a date like 2011-11-30 to a LocalDateTime (with a default time)?

    1. Parse it first in a LocalDate
    2. Use LocalDateTime atTime() method to set your default time

    Note: Use of DateTimeFormatter.ISO_LOCAL_DATE is superfluous for parse(), see API LocalDate#parse()