1

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.

mars8
  • 770
  • 1
  • 11
  • 25
  • 1
    The hack is to insert the `T` yourself: `"2023-05-10 09:41:00".replace(' ', 'T')`. This will allow you to use the existing formatter constant. The solution is to construct your own formatter for parsing, for example `DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss")`. – Ole V.V. May 10 '23 at 15:23
  • 1
    But I agree that it is better to use the built-in formatters. We can. It gets a bit wordier, but personally I find it worth it: `new DateTimeFormatterBuilder() .append(DateTimeFormatter.ISO_LOCAL_DATE) .appendLiteral(' ') .append(DateTimeFormatter.ISO_LOCAL_TIME) .toFormatter()` – Ole V.V. May 10 '23 at 15:27

1 Answers1

1

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.

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110