7.8 Java8新增的日期 时间格式器
Java8新增的日期、时间API里不仅包括了Instant、 LocalDate、 LocalDateTime、 LocalTime等代表日期、时间的类,而且在Java.time.format包下提供了一个DateTimeFormatter格式器类,该类相当于前面介绍的DateFormat和SimpleDateFormat的合体,功能非常强大。
与DateFormat、 SimpleDateFormat类似, DateTimeFormatter不仅可以将日期、时间对象格式化成字符串,也可以将特定格式的字符串解析成日期、时间对象。
获取DateTimeFormatter对象的方式
为了使用DateTimeFormatter进行格式化或解析,必须先获取DateTimeFormatter对象,获取DateTimeFormatter对象有如下三种常见的方式。
- 直接使用静态常量创建
DateTimeFormatter格式器。Date Time Formatter类中包含了大量形如ISO_LOCAL_DATE、ISO_LOCAL_TIME、ISO_LOCAL_DATE_TIME等静态常量,这些静态常量本身就是DateTimeFormatter实例。 - 使用代表不同风格的
枚举值来创建DateTimeFormatter格式器。在FormatStyle枚举类中定义了FULL、LONG、MEDIUM、SHORT四个枚举值,它们代表日期、时间的不同风格. - 根据
模式字符串来创建DateTimeFormatter格式器。类似于SimpleDateFormat,可以采用模式字符串来创建DateTimeFormatter,如果需要了解DateTimeFormatter支持哪些模式字符串,则需要参考该类的API文档。
7.8.1 使用DateTimeFormatter完成格式化
使用DateTimeFormatter将日期、时间(LocalDate、 LocalDateTime、 LocalTime等实例)格式化为字符串,可通过如下两种方式。
- 调用
DateTimeFormatter的formate(TemporalAccessor temporal)方法执行格式化,其中LocalDate,LocalDateTime、LocalTime等类都是TemporalAccessor接口的实现类。 - 调用
LocalDate、LocalDate Time、LocalTime等日期、时间对象的format(DateTimeFormatter formatter)方法执行格式化。
程序示例
上面两种方式的功能相同,用法也基本相似,如下程序示范了使用DateTimeFormatter来格式化日期、时间:
1 | import java.time.*; |
1 | 2019-10-06 |
DateTimeFormatter功能更强大
使用DateTimeFormatter进行格式化时不仅可按系统预置的格式对日期、时间进行格式化,也可使用模式字符串对日期、时间进行自定义格式化,由此可见, DateTimeFormatter的功能完全覆盖了传统的DateFormat、 SimpleDateFormate的功能。
DateTimeFormatter怎么转DateFormat
有些时候,读者可能还需要使用传统的DateFormat来执行格式化, DateTimeFormatter则提供了一个toFormat()方法,该方法可以获取DateTimeFormatter对应的Format对象。