Java 8 date is equivalent to joda’s datetimeformatterbuilder, which has multiple parser formats?

I currently have a joda date parser that uses datetimeformatterbuilder and can receive six different date formats

I'm migrating to the date routine of Java 8. I can't see the equivalent

How to use Java 8 date to do such a thing?

DateTimeParser[] parsers = { 
    DateTimeFormat.forPattern( "yyyy/MM/dd HH:mm:ss.SSSSSS" ).getParser(),DateTimeFormat.forPattern( "yyyy-MM-dd HH:mm:ss" ).getParser(),DateTimeFormat.forPattern( "ddMMMyyyy:HH:mm:ss.SSS Z" ).getParser(),DateTimeFormat.forPattern( "ddMMMyyyy:HH:mm:ss.SSS" ).getParser(),DateTimeFormat.forPattern( "ddMMMyyyy:HH:mm:ss.SSSSSS" ).getParser(),DateTimeFormat.forPattern( "yyyy-MM-dd HH:mm:ss.SSS" ).getParser() 
};

DateTimeFormatter dateTimeFormatterInput = new DateTimeFormatterBuilder()
     .append( null,parsers ).toFormatter();

Solution

There is no direct way to do this, but you can use the optional part The optional parts are enclosed in square brackets [] This allows the entire part of the string to be resolved as missing

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(""
    + "[yyyy/MM/dd HH:mm:ss.SSSSSS]"
    + "[yyyy-MM-dd HH:mm:ss[.SSS]]"
    + "[ddMMMyyyy:HH:mm:ss.SSS[ Z]]"
);

This formatter defines three optional parts for the three main patterns you have Each of them is in their own optional part

Work demonstration code:

public static void main(String[] args) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(""
        + "[yyyy/MM/dd HH:mm:ss.SSSSSS]"
        + "[yyyy-MM-dd HH:mm:ss[.SSS]]"
        + "[ddMMMyyyy:HH:mm:ss.SSS[ Z]]",Locale.ENGLISH);
    System.out.println(LocalDateTime.parse("2016/03/23 22:00:00.256145",formatter));
    System.out.println(LocalDateTime.parse("2016-03-23 22:00:00",formatter));
    System.out.println(LocalDateTime.parse("2016-03-23 22:00:00.123",formatter));
    System.out.println(LocalDateTime.parse("23Mar2016:22:00:00.123",formatter));
    System.out.println(LocalDateTime.parse("23Mar2016:22:00:00.123 -0800",formatter));
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>