DateTimeFormatter学习参考
2019-10-26 本文已影响0人
kiki的进阶之路
首先贴上官网链接DateTimeFormatter
DateTimeFormatter提供三种方式完成格式化:
- 预定义
- 模式字符串
- 本地化风格
下面对这三种模式详细介绍
预定义
先看例子:
jshell> LocalDateTime ldt = LocalDateTime.now();
ldt ==> 2019-10-25T14:21:35.146187
jshell> DateTimeFormatter dtf = DateTimeFormatter.BASIC_ISO_DATE;
dtf ==> ParseCaseSensitive(false)Value(Year,4)Value(Month ... Mss,'Z')ParseStrict(true)]
jshell> String dateNow = ldt.format(dtf);
dateNow ==> "20191025"
jshell> LocalDateTime ldt = LocalDateTime.now();
ldt ==> 2019-10-25T14:18:08.339930
jshell> DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE;
dtf ==> ParseCaseSensitive(false)(Value(Year,4,10,EXCEEDS ... 2))[Offset(+HH:MM:ss,'Z')]
jshell> String dateNow = ldt.format(dtf);
dateNow ==> "2019-10-25"
Formatter | Example |
---|---|
BASIC_ISO_DATE |
'20111203' |
ISO_LOCAL_DATE |
'2011-12-03' |
ISO_OFFSET_DATE |
'2011-12-03+01:00' |
ISO_DATE |
'2011-12-03+01:00'; '2011-12-03' |
ISO_LOCAL_TIME |
'10:15:30' |
ISO_OFFSET_TIME |
'10:15:30+01:00' |
ISO_TIME |
'10:15:30+01:00'; '10:15:30' |
ISO_LOCAL_DATE_TIME |
'2011-12-03T10:15:30' |
ISO_OFFSET_DATE_TIME |
2011-12-03T10:15:30+01:00' |
ISO_ZONED_DATE_TIME |
'2011-12-03T10:15:30+01:00[Europe/Paris]' |
ISO_DATE_TIME |
'2011-12-03T10:15:30+01:00[Europe/Paris]' |
ISO_ORDINAL_DATE |
'2012-337' |
ISO_WEEK_DATE |
2012-W48-6' |
ISO_INSTANT |
'2011-12-03T10:15:30Z' |
模式字符串
yyyy-MM-dd HH:mm:ss:SSS
HH大写代表24小时制
hh小写代表12小时制
yyyy-MM-dd hh:mm:ss:SSS a
例子:
//实例化
jshell> LocalDateTime ld = LocalDateTime.now();
ld ==> 2019-10-25T14:36:03.166545
//"yyyy-MM-dd"
jshell> DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
dtf ==> Value(YearOfEra,4,19,EXCEEDS_PAD)'-'Value(MonthOfYear,2)'-'Value(DayOfMonth,2)
jshell> String dateNow = ld.format(dtf);
dateNow ==> "2019-10-25"
//"HH:mm:ss:SSS"
jshell> DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss:SSS");
dtf ==> Value(HourOfDay,2)':'Value(MinuteOfHour,2)':'Valu ... Fraction(NanoOfSecond,3,3)
jshell> String dateNow = ld.format(dtf);
dateNow ==> "14:36:03:166"
//"yyyy-MM-dd HH:mm:ss:SSS"
jshell> DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS");
dtf ==> Value(YearOfEra,4,19,EXCEEDS_PAD)'-'Value(MonthOf ... Fraction(NanoOfSecond,3,3)
jshell> String dateNow = ld.format(dtf);
dateNow ==> "2019-10-25 14:36:03:166"