DateTimeFormatter to parse all ISO-valid styles of zone-offset [duplicate]

北城余情 提交于 2019-12-11 07:33:16

问题


With the following formatter I'm able to parse "2017-03-28T23:40:06.000+0100"

new DateTimeFormatterBuilder()
            .append(ISO_LOCAL_DATE_TIME)
            .appendPattern("X")
            .toFormatter();

With another one it parses "2017-03-28T23:40:06.000+01:00"

new DateTimeFormatterBuilder()
            .append(ISO_LOCAL_DATE_TIME)
            .appendPattern("XX")
            .toFormatter();

However, I'm unable to specify formatter that parses both. What pattern should I append?

Formatter should also be able to process timestamps without zone-offset, e.g. "2017-03-28T23:40:06.000Z"


回答1:


Since the DateTimeFormatterBuilder behaves like a fluent interface, the easiest way is to append both of the patterns:

new DateTimeFormatterBuilder()
        .append(ISO_LOCAL_DATE_TIME)
        .appendPattern("X")
        .appendPattern("XX")
        .toFormatter();



回答2:


The following started to work for me

new DateTimeFormatterBuilder()
            .append(ISO_LOCAL_DATE_TIME)
            .optionalStart()
            .appendPattern("[XXX][X]")
            .toFormatter();



回答3:


I once had a task to parse any String to Date if the String represent a valid Date not knowing format in advance. Basically I needed to format String of any possible format. I came up with an idea where you write into a file all data formats that you wish to support and then read the formats one by one and try to parse a String by that format until you succeed or run out of formats. Here is the link to the article that describe the idea in more detail: Java 8 java.time package: parsing any string to date



来源:https://stackoverflow.com/questions/55807603/datetimeformatter-to-parse-all-iso-valid-styles-of-zone-offset

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