SimpleDateFormat和DateTimeFormatter的区别

发布时间 2023-09-21 21:03:00作者: 达摩院的BLOG

1、简介
  DateTimeFormatter 和 SimpleDateFormat 都是用于格式化日期和时间的类,但是它们有一些区别。

  SimpleDateFormat 是 Java 早期版本中提供的日期格式化类,他是线程不安全的。由于 SimpleDateFormat 是线程不安全的,所以如果在多线程环境中使用会出现异常,通常的解决方法要么是每个线程独立维护一份 SimpleDateFormat 对象实例,要么是将 SimpleDateFormat 放到 ThreadLocal 中。

  在Java 8中新增了DateTimeFormatter 类,它比 SimpleDateFormat 更加灵活和安全。DateTimeFormatter 是不变对象,且是线程安全的。所以在使用 DateTimeFormatter 的时候,可以以静态成员变量的方式,在一个类中只维护一份对象实例,用于格式化多个日期和时间值,而无需担心线程安全问题。

2、区别

DateTimeFormatter 和 SimpleDateFormat 都是 Java 中用于日期和时间格式化的类,但它们之间存在以下区别:

线程安全性:DateTimeFormatter 是线程安全的,而 SimpleDateFormat 不是。

类型支持:DateTimeFormatter 支持多种日期和时间类型,例如 LocalDate、LocalTime、LocalDateTime、ZonedDateTime、OffsetDateTime 等。而 SimpleDateFormat 只支持 Date 类型。

解析能力:DateTimeFormatter 可以将字符串解析为日期和时间类型,而 SimpleDateFormat 不支持解析操作。

本地化:DateTimeFormatter 支持本地化,可以根据不同的语言和国家的习惯格式化日期和时间。而 SimpleDateFormat 也支持本地化,但使用较为麻烦。

例如,要将日期格式化为法国本地化格式,可以使用以下代码:

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.FRANCE);
LocalDate date = LocalDate.now();
String formattedDate = date.format(formatter);
System.out.println(formattedDate);

 

 扩展:JAVA时间工具类【DateTimeFormatter】