Search code examples
javadatetimelocaltime

LocalDateTime : converting String to HH:mm:ss


What I need to do :
I need to pass a LocalDateTime object to a constructor and I have a string that have "18:14:00" as value.

My question :
How can I convert the string to LocalDateTime ?

What I have done :
After some researches, I put this but it didn't work :

LocalDateTime.parse("18:14:00", DateTimeFormatter.ofPattern("HH:mm:ss"));

java.time.format.DateTimeParseException: Text '18:14:00' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 18:14 of type java.time.format.Parsed


Solution

  • The "Unable to obtain LocalDateTime" exception is because the parsed text only has time values, no date values, so it is impossible to construct a Local​Date​Time object.

    Parse to a LocalTime instead:

    LocalTime time = LocalTime.parse("18:14:00");
    
    System.out.println(dateTime); // Prints: 18:14
    

    The "HH:mm:ss" pattern is the default for a LocalTime, so there is no need to specify it (see: DateTimeFormatter.ISO_LOCAL_TIME).

    If you want/need a LocalDateTime object, parsed similarly to how SimpleDateFormat did it, i.e. defaulting the Jan 1, 1970, then you need to explicitly specify the default date value:

    DateTimeFormatter fmt = new DateTimeFormatterBuilder()
            .append(DateTimeFormatter.ISO_LOCAL_TIME)
            .parseDefaulting(ChronoField.EPOCH_DAY, 0)
            .toFormatter();
    LocalDateTime dateTime = LocalDateTime.parse("18:14:00", fmt);
    
    System.out.println(dateTime); // Prints: 1970-01-01T18:14
    

    For comparison, that is equivalent to the old SimpleDateFormat result:

    Date date = new SimpleDateFormat("HH:mm:ss").parse("18:14:00");
    
    System.out.println(date); // Prints: Thu Jan 01 18:14:00 EST 1970