Parsing an ISO 8601 date in Java8 when all fields (including separators, but not including years) are optional

前端 未结 4 1668
北海茫月
北海茫月 2021-01-15 06:26

I have a requirement for parsing ISO8601 formatted strings in Java with various levels of accuracy. Some examples of the string I need to parse are:

  • 2018
4条回答
  •  粉色の甜心
    2021-01-15 06:57

    For the first cases with separators (-, :) one can use:

        DateTimeFormatter dtf = DateTimeFormatter
            .ofPattern("uuuu[-MM[-dd[['T']HH[:]mm[[:]ss[[.]SSS]]]]]");
        ParsePosition pos = new ParsePosition(0);
        TemporalAccessor result = dtf.parse(text, pos);
    

    However neither uuuuMMdd nor [-] or ['-'] worked for me in Java 8.

提交回复
热议问题