how to parse OffsetTime for format HHmmssZ

ぐ巨炮叔叔 提交于 2021-02-11 17:09:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!