Convert string into LocalDateTime

2020-02-14 18:50发布

问题:

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?

回答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"));


回答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);


回答3:

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".



回答4:

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



回答5:

Just use LocalDate instead of LocalDateTime