Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

java - How to unify date format using DateTimeFormatter

I need to parse different time format into BASIC_ISO_DATE. Right now, there are 4 types of date format:

  • 2016-10-01 (ISO_LOCAL_DATE)
  • 2016T
  • 201610T
  • 2016-02-07T22:03:39.937Z (ISO 8601)

Need to parse to 20161001 and print out, with default day is 01, default month Jan. Examples:

  • 2016T -> 20160101
  • 201610T -> 20161001

How can I use DateTimeFormatter to achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just to complement @Flown's answer (which works perfectly BTW), you can also use optional patterns (delimited by []):

DateTimeFormatter parser = new DateTimeFormatterBuilder()
    // optional ISO8601 date/time and offset
    .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
    // optional yyyy-MM-dd or yyyyT or yyyyMMT
    .appendPattern("[yyyy-MM-dd][yyyy'T'][yyyyMM'T']")
    // default day is 1
    .parseDefaulting(ChronoField.DAY_OF_MONTH, 1L)
    // default month is January
    .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1L)
    // create formatter
    .toFormatter();

This works exactly the same way. You can choose which one is clearer or easier to maintain. If there are lots of different patterns, using [] might end up being more confusing, IMO.

Note that I used ISO_OFFSET_DATE_TIME instead of ISO_ZONED_DATE_TIME. The only difference is that ISO_ZONED_DATE_TIME also accepts a timezone name in the end (like [Europe/London]), while ISO_OFFSET_DATE_TIME doesn't. Check the javadoc for more info.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...