问题
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)
回答1:
All the following will return a LocalTime
with value 11:56:01
:
LocalTime.parse("115601Z", DateTimeFormatter.ofPattern("HHmmss'Z'"))
OffsetTime.parse("115601Z", DateTimeFormatter.ofPattern("HHmmssX")).toLocalTime()
OffsetTime.parse("115601Z", DateTimeFormatter.ofPattern("HHmmssXX")).toLocalTime()
OffsetTime.parse("115601Z", DateTimeFormatter.ofPattern("HHmmssXXX")).toLocalTime()
OffsetTime.parse("115601Z", DateTimeFormatter.ofPattern("HHmmssXXXX")).toLocalTime()
OffsetTime.parse("115601Z", DateTimeFormatter.ofPattern("HHmmssXXXXX")).toLocalTime()
OffsetTime.parse("115601Z", DateTimeFormatter.ofPattern("HHmmssZZZZZ")).toLocalTime()
回答2:
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.
来源:https://stackoverflow.com/questions/59705911/how-to-parse-offsettime-for-format-hhmmssz