I know this has been asked before, but I still have an error after looking at all the solutions.
I'm trying to parse a String to a LocalDateTime using a DateTimeFormatter.
This is my code:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class MainAppointment {
public static void main(String[] args) {
String description = "12/02/2024 13:45:00";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime result = LocalDateTime.parse(description,parser);
}
}
And the error I get is
Exception in thread "main" java.time.format.DateTimeParseException: Text '12/02/2023 13:45:00' could not be parsed at index 0
I've tried changing the DateTimeFormatter pattern to yyyy-MM-dd'T'HH:mm:ss
and I even tried using .ISO_LOCAL_DATE_TIME
instead of the ofPattern. And I still get the same error.
What am I doing wrong? It seems to be ok (I read a lot of other questions and tried the solutions).
Your matches for the parser are wrong, try this:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class MainAppointment {
public static void main(String[] args) {
String description = "12/02/2024 13:45:00";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
LocalDateTime result = LocalDateTime.parse(description,parser);
}
}