Java 8 Date equivalent to Joda's DateTimeFormatterBuilder with multiple parser formats?

后端 未结 5 1024
我寻月下人不归
我寻月下人不归 2020-12-09 08:50

I currently have a Joda date parser that uses the DateTimeFormatterBuilder with half a dozen different date formats that I may receive.

I\'m migrating to Java 8\'s D

5条回答
  •  独厮守ぢ
    2020-12-09 09:11

    Here is what I eventually came up with. It handles three different major formats, each with multiple minor formatting differences (such as allowing either - or / delimiters) as well as handling variable number of microseconds (from 0 to 6):

    private static final DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern( "[ddMMMyyyy:HH:mm:ss" )
            .optionalStart()
            .appendFraction( ChronoField.MICRO_OF_SECOND , 1 , 6 , true )
            .optionalEnd()
            .appendPattern( "[ ][Z][X]]" )
            .appendPattern( "[yyyy[-][/]MM[-][/]dd['T'][ ]HH:mm[:][.]ss" )
            .optionalStart()
            .appendFraction( ChronoField.MICRO_OF_SECOND , 1 , 6 , true )
            .optionalEnd()
            .appendPattern( "[Z][X]]" )
            .appendPattern( "[EEE, dd MMM yyyy HH:mm:ss zzz]" )
            .toFormatter();
    

提交回复
热议问题