I am trying to parse string "2023-05-10 09:41:00" to LocalTime using java.time library.
When I try LocalTime.parse("2023-05-10 09:41:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME)
I get java.time.format.DateTimeParseException
. However when I try LocalTime.parse("2023-05-10T09:41:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME)
it works.
Is there any DateTimeFormatter
constant I can use that works without the "T" separator? I am aware I can use a custom DateTimeFormatter but I would like to use a prepackaged constant from java or kotlin library like pseudo code DateTimeFormatter.ISO_LOCAL_DATE_TIME_WIHOUT_T
.
Is there any
DateTimeFormatter
constant I can use that works without the "T" separator?
There is none because java.time
is based on ISO 8601 which uses a date-time string with T
as the time separator.
However, you can achieve it with some hacks (just for fun, not for production code).
Demo
public class Main {
public static void main(String[] args) {
String strDateTime = "2023-05-10 09:41:00";
ParsePosition position = new ParsePosition(strDateTime.indexOf(' ') + 1);
LocalTime time = LocalTime.from(DateTimeFormatter.ISO_LOCAL_TIME.parse(strDateTime, position));
System.out.println(time);
}
}
Output:
09:41
There is another hack which Ole V.V. has already mentioned in his comment.
Learn more about the modern Date-Time API from Trail: Date Time.