DateTimeFormatter
使用旧的Date
对象时,我们用SimpleDateFormat
进行格式化显示。使用新的LocalDateTime
或ZonedLocalDateTime
时,我们要进行格式化显示,就要使用DateTimeFormatter
。
和SimpleDateFormat
不同的是,DateTimeFormatter
不但是不变对象,它还是线程安全的。线程的概念我们会在后面涉及到。现在我们只需要记住:因为SimpleDateFormat
不是线程安全的,使用的时候,只能在方法内部创建新的局部变量。而DateTimeFormatter
可以只创建一个实例,到处引用。
创建DateTimeFormatter
时,我们仍然通过传入格式化字符串实现:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
格式化字符串的使用方式与SimpleDateFormat
完全一致。
另一种创建DateTimeFormatter
的方法是,传入格式化字符串时,同时指定Locale
:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E, yyyy-MMMM-dd HH:mm", Locale.US);
这种方式可以按照Locale
默认习惯格式化。我们来看实际效果:
在格式化字符串中,如果需要输出固定字符,可以用'xxx'
表示。
运行上述代码,分别以默认方式、中国地区和美国地区对当前时间进行显示,结果如下:
-09-15T23:16 GMT+08:00
9月 15 周日 23:16
Sun, September/15/2019 23:16
当我们直接调用System.out.println()
对一个ZonedDateTime
或者LocalDateTime
实例进行打印的时候,实际上,调用的是它们的toString()
方法,默认的toString()
方法显示的字符串就是按照ISO 8601
格式显示的,我们可以通过DateTimeFormatter
预定义的几个静态变量来引用:
var ldt = LocalDateTime.now();
System.out.println(DateTimeFormatter.ISO_DATE.format(ldt));
System.out.println(DateTimeFormatter.ISO_DATE_TIME.format(ldt));
得到的输出和toString()
类似:
-09-15
-09-15T23:16:51.56217
小结
对ZonedDateTime
或LocalDateTime
进行格式化,需要使用DateTimeFormatter
类;
DateTimeFormatter
可以通过格式化字符串和Locale
对日期和时间进行定制输出。
读后有收获可以支付宝请作者喝咖啡,读后有疑问请加微信群讨论
看完两件小事
如果你觉得这篇文章对你挺有启发,我想请你帮我两个小忙:
- 把这篇文章分享给你的朋友 / 交流群,让更多的人看到,一起进步,一起成长!
- 关注公众号 「方志朋」,公众号后台回复「资源」 免费领取我精心整理的前端进阶资源教程