如何使用DateTimeFormatter统一日期格式 [英] How to unify date format using DateTimeFormatter
问题描述
我需要将不同的时间格式解析为 BASIC_ISO_DATE
。现在,有4种类型的日期格式:
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)
2016-10-01
(ISO_LOCAL_DATE)2016T
201610T
2016-02-07T22:03:39.937Z
(ISO 8601)
需要解析为 20161001
并打印出来,默认日期为 01
,默认月 Jan
。示例:
Need to parse to 20161001
and print out, with default day is 01
, default month Jan
. Examples:
-
2016T
- >20160101
-
201610T
- >20161001
2016T
->20160101
201610T
->20161001
如何使用 DateTimeFormatter
来实现这一目标?
How can I use DateTimeFormatter
to achieve this?
推荐答案
只是为了补充 @Flown的回答(这完全适用于BTW ),你也可以使用可选模式(由 []
分隔):
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();
这种方式完全相同。您可以选择哪一个更清晰或更容易维护。如果有批次的不同模式,使用 []
可能会让人更加困惑,IMO。
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.
请注意,我使用 ISO_OFFSET_DATE_TIME
而不是 ISO_ZONED_DATE_TIME
。唯一的区别是 ISO_ZONED_DATE_TIME
最后也接受时区名称(如 [Europe / London]
),而 ISO_OFFSET_DATE_TIME
没有。 查看javadoc 了解更多信息。
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.
这篇关于如何使用DateTimeFormatter统一日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!