0%

7.8 Java8新增的日期 时间格式器 7.8.1 使用DateTimeFormatter完成格式化

7.8 Java8新增的日期 时间格式器

Java8新增的日期、时间API里不仅包括了InstantLocalDateLocalDateTimeLocalTime等代表日期、时间的类,而且在Java.time.format包下提供了一个DateTimeFormatter格式器类,该类相当于前面介绍的DateFormatSimpleDateFormat的合体,功能非常强大。
DateFormatSimpleDateFormat类似, DateTimeFormatter不仅可以将日期、时间对象格式化成字符串,也可以将特定格式的字符串解析成日期、时间对象。

获取DateTimeFormatter对象的方式

为了使用DateTimeFormatter进行格式化或解析,必须先获取DateTimeFormatter对象,获取DateTimeFormatter对象有如下三种常见的方式。

  1. 直接使用静态常量创建DateTimeFormatter格式器。 Date Time Formatter类中包含了大量形如ISO_LOCAL_DATEISO_LOCAL_TIMEISO_LOCAL_DATE_TIME等静态常量,这些静态常量本身就是DateTimeFormatter实例。
  2. 使用代表不同风格的枚举值来创建DateTimeFormatter格式器。在FormatStyle枚举类中定义了FULLLONGMEDIUMSHORT四个枚举值,它们代表日期、时间的不同风格.
  3. 根据模式字符串来创建DateTimeFormatter格式器。类似于SimpleDateFormat,可以采用模式字符串来创建DateTimeFormatter,如果需要了解DateTimeFormatter支持哪些模式字符串,则需要参考该类的API文档。

7.8.1 使用DateTimeFormatter完成格式化

使用DateTimeFormatter将日期、时间(LocalDateLocalDateTimeLocalTime等实例)格式化为字符串,可通过如下两种方式。

  1. 调用DateTimeFormatterformate(TemporalAccessor temporal)方法执行格式化,其中LocalDate,LocalDateTimeLocalTime等类都是TemporalAccessor接口的实现类。
  2. 调用LocalDateLocalDate TimeLocalTime等日期、时间对象的format(DateTimeFormatter formatter)方法执行格式化。

程序示例

上面两种方式的功能相同,用法也基本相似,如下程序示范了使用DateTimeFormatter来格式化日期、时间:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.time.*;
import java.time.format.*;

public class NewFormatterTest {
public static void main(String[] args) {
// 创建DateTimeFormatter对象数组
DateTimeFormatter[] formatters = new DateTimeFormatter[] {
// 直接使用常量创建DateTimeFormatter格式器
DateTimeFormatter.ISO_LOCAL_DATE, DateTimeFormatter.ISO_LOCAL_TIME,
DateTimeFormatter.ISO_LOCAL_DATE_TIME,
// 使用本地化的不同风格来创建DateTimeFormatter格式器
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.MEDIUM),
DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG),
// 根据模式字符串来创建DateTimeFormatter格式器
DateTimeFormatter.ofPattern("Gyyyy%%MMM%%dd HH:mm:ss") };

LocalDateTime date = LocalDateTime.now();
// 依次使用不同的格式器对LocalDateTime进行格式化
for (int i = 0; i < formatters.length; i++) {
// 下面两行代码的作用相同
System.out.println(date.format(formatters[i]));
System.out.println(formatters[i].format(date));
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2019-10-06
2019-10-06
18:57:24.3196636
18:57:24.3196636
2019-10-06T18:57:24.3196636
2019-10-06T18:57:24.3196636
2019年10月6日星期日 下午6:57:24
2019年10月6日星期日 下午6:57:24
2019年10月6日
2019年10月6日
公元2019%%10月%%06 18:57:24
公元2019%%10月%%06 18:57:24

DateTimeFormatter功能更强大

使用DateTimeFormatter进行格式化时不仅可按系统预置的格式对日期、时间进行格式化,也可使用模式字符串对日期、时间进行自定义格式化,由此可见, DateTimeFormatter的功能完全覆盖了传统的DateFormatSimpleDateFormate的功能。

DateTimeFormatter怎么转DateFormat

有些时候,读者可能还需要使用传统的DateFormat来执行格式化, DateTimeFormatter则提供了一个toFormat()方法,该方法可以获取DateTimeFormatter对应的Format对象。

原文链接: 7.8 Java8新增的日期 时间格式器 7.8.1 使用DateTimeFormatter完成格式化