User0911
User0911

Reputation: 1582

Conversion of string to LocalDateTime in Java 8

How to convert a string "23:00" to LocalDateTime in Java 8? This doesn't seems to be working,

LocalDateTime dateTime1 = LocalDateTime.parse("23:00", DateTimeFormatter.ofPattern("HH:mm"));

This is the exception that is thrown,

java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 23:00 of type java.time.format.Parsed

Upvotes: 1

Views: 1023

Answers (2)

JB Nizet
JB Nizet

Reputation: 692231

You only pass time information to the parser, and it needs to create a LocalDateTime. The parser can't guess which Date part you want for the LocateDateTime.

Use

LocalDateTime time = 
    LocalTime.parse("23:00", DateTimeFormatter.ofPattern("HH:mm"))
        .atDate(LocalDate.now());

for example, if you want today at 23:00.

Upvotes: 8

Erik Pragt
Erik Pragt

Reputation: 14677

You can't. As from the documentation:

LocalDate stores a date without a time. This stores a date like '2010-12-03' and could be used to store a birthday.

LocalTime stores a time without a date. This stores a time like '11:30' and could be used to store an opening or closing time.

LocalDateTime stores a date and time. This stores a date-time like '2010-12-03T11:30'.

So, if you want to do that, you'll need to create a LocalTime instead. If you really need a LocalDateTime, use this instead: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#of-java.time.LocalDate-java.time.LocalTime-

Upvotes: 2

Related Questions