Convert string into LocalDateTime

I have the following String:

18/07/2019 16:20

I try to convert this string into LocalDateTime with the following code:

val stringDate = expiration_button.text.toString()
val date = LocalDateTime.parse(stringDate, DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm")).toString()

java.time.format.DateTimeParseException: Text '18/07/2019 04:30:00' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor

What I'm missing?


Solution 1:

I think this will answer your question:

val stringDate = expiration_button.text.toString()
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm");
val dt = LocalDate.parse(stringDate, formatter);

Edit 1:

It's probably crashing because you are using a 12hr Hour, instead of a 24hr pattern.

Changing the hour to 24hr pattern by using a capital H should fix it:

val dateTime = LocalDateTime.parse(stringDate, DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"));

Solution 2:

Use below to convert the time from String to LocalDateTime, but make sure you are getting the time in String form.

String str = "2016-03-04 11:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

Btw, If your String contains seconds as well like "2016-03-04 11:30: 40", then you can change your date time format to yyyy-MM-dd HH:mm:ss" as shown below:

String str = "2016-03-04 11:30: 40";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);