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?
Parsing String to LocalDateparse() method takes two arguments. The first argument is the string representing the date. And the second optional argument is an instance of DateTimeFormatter specifying any custom pattern. //Default pattern is yyyy-MM-dd LocalDate today = LocalDate.
Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.
If we want to display the time zone offset, we can use the formatter “Z” or “X”: DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy - HH:mm:ss Z"); String formattedString = zonedDateTime.format(formatter); This would give us a result like this: 02/01/2018 - 13:45:30 +0000.
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With