Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to parse date string with format "HHmmssZ",

OffsetTime.parse("115601Z", DateTimeFormatter.ofPattern("HHmmssZ")).toLocalTime()

when i test it i get the exception :

java.time.format.DateTimeParseException: Text '112322Z' could not be parsed at index 6

    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.OffsetTime.parse(OffsetTime.java:327)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
125 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use pattern letter uppercase X for an offset that may use Z for zero

    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HHmmssXXX");
    OffsetTime time = OffsetTime.parse("115601Z", timeFormatter);
    System.out.println(time);

Output from this snippet is:

11:56:01Z

To convert to LocalTime just use .toLocalTime() as you are already doing.

For pattern letter Z give offset as +0000

Edit: As you mentioned in the comment, the opposite way to repair the situation is to keep the format pattern string and parse a string that matches the required format:

    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HHmmssZ");
    OffsetTime time = OffsetTime.parse("115601+0000", timeFormatter);

The result is the same as before. One uppercase letter Z in the format pattern string matches (quoting the documentation):

… the hour and minute, without a colon, such as '+0130'.

Link

Documentaion of DateTimeFormatter and the pattern letters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...