Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 837
Lechucico Avatar asked Jul 18 '19 14:07

Lechucico


People also ask

How do I convert a string to LocalDate?

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.

How do I convert a string to a date?

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.

What is Z in LocalDateTime?

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.


Video Answer


1 Answers

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"));
like image 140
Alex Avatar answered Sep 25 '22 07:09

Alex