16

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?

Lechucico
  • 1,914
  • 7
  • 27
  • 60
  • 1
    Maybe this one can help -> https://stackoverflow.com/questions/27454025/unable-to-obtain-localdatetime-from-temporalaccessor-when-parsing-localdatetime – Róbert Polovitzer Jul 18 '19 at 14:27
  • Possible duplicate of [DateTimeParseException: Text '2019-06-07 12:18:16' could not be parsed](https://stackoverflow.com/questions/56500476/datetimeparseexception-text-2019-06-07-121816-could-not-be-parsed) – Ole V.V. Jul 19 '19 at 11:00

4 Answers4

19

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"));
Alex
  • 962
  • 4
  • 15
3

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);
0

Change your datetime format to "dd/MM/yyyy hh:mm a" and provide a string date with additional AM/PM information, e.g. val stringDate = "18/07/2019 04:20 PM" or just use the 24 hour format "dd/MM/yyyy HH:mm".

jsamol
  • 3,042
  • 2
  • 16
  • 27
  • If on one hand the string is given, `18/07/2019 16:20`, modifying it is this way is not trivial. If on the other hand it is possible to get a different string, I would suggest a string in [ISO 8601 format](https://en.wikipedia.org/wiki/ISO_8601), so `2019-07-18T16:20`. `LocalDateTime` will parse such a string without any explicit formatter, simplifying things. – Ole V.V. Jul 19 '19 at 11:05
-2

You may try using "-" instead of "/" on the date.

Davis
  • 137
  • 1
  • 6