java - How to unify date format using DateTimeFormatter -
i need parse different time format basic_iso_date
. right now, there 4 types of date format:
2016-10-01
(iso_local_date)2016t
201610t
2016-02-07t22:03:39.937z
(iso 8601)
need parse 20161001
, print out, default day 01
, default month jan
. examples:
2016t
->20160101
201610t
->20161001
how can use datetimeformatter
achieve this?
just complement @flown's answer (which works btw), can use optional patterns (delimited []
):
datetimeformatter parser = new datetimeformatterbuilder() // optional iso8601 date/time , 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 1 .parsedefaulting(chronofield.day_of_month, 1l) // default month january .parsedefaulting(chronofield.month_of_year, 1l) // create formatter .toformatter();
this works same way. can choose 1 clearer or easier maintain. if there lots of different patterns, using []
might end being more confusing, imo.
note used iso_offset_date_time
instead of iso_zoned_date_time
. difference iso_zoned_date_time
accepts timezone name in end (like [europe/london]
), while iso_offset_date_time
doesn't. check javadoc more info.
Comments
Post a Comment