迁移到新的 Java 8 日期时间 API

1. 概述

在本教程中,您将学习如何重构代码以利用 Java 8 中引入的新日期时间 API。

2. 新 API 概览

在 Java 中使用日期过去很困难。JDK提供的旧日期库仅包含三个类:java.util.Date,java.util.Calendarjava.util.Timezone

这些仅适用于最基本的任务。对于任何远程复杂的内容,开发人员必须使用第三方库或编写大量自定义代码。

Java 8引入了一个全新的Date Time APIjava.util.time.*),它大致基于流行的Java库JodaTime。这个新的 API 极大地简化了日期和时间处理,并修复了旧日期库的许多缺点。

1.1. 接口清晰度

新 API 的第一个优点是清晰——API 非常清晰、简洁且易于理解。它在旧库中没有发现很多不一致之处,例如字段编号(在日历月中从零开始,但星期几是从 1 开始的)。

1.2. 接口灵活性

另一个优点是灵活性 - 使用多种时间表示形式。旧的日期库只包含一个时间表示类 - java.util.Date,尽管它的名字,实际上是一个时间戳。它仅存储自 Unix 纪元以来经过的毫秒数。

新的 API 有许多不同的时间表示形式,每种表示形式都适用于不同的用例:

  • Instant  – 表示时间点(时间戳)
  • LocalDate  – 表示日期(年、月、日)
  • LocalDateTime – 与LocalDate 相同,但包括具有纳秒精度的时间
  • OffsetDateTime – 与本地日期时间相同,但具有时区偏移量
  • LocalTime  – 具有纳秒精度且没有日期信息的时间
  • ZonedDateTime – 与OffsetDateTime 相同,但包括时区 ID
  • OffsetLocalTime – 与LocalTime 相同,但具有时区偏移量
  • MonthDay  – 月和日,没有年或时间
  • YearMonth– 月和年,没有日期或时间
  • Duration –以秒,分钟和小时表示的时间量。具有纳秒级精度
  • Period  – 以天、月和年表示的时间量

1.3. 不变性和线程安全

另一个优点是 Java 8 日期时间 API 中的所有时间表示都是不可变的,因此是线程安全的。

所有可变方法都返回一个新副本,而不是修改原始对象的状态。

java.util.Date这样的旧类不是线程安全的,并且可能会引入非常微妙的并发错误。

1.4. 方法链

所有变异方法都可以链接在一起,允许在一行代码中实现复杂的转换。

ZonedDateTime nextFriday = LocalDateTime.now()
  .plusHours(1)
  .with(TemporalAdjusters.next(DayOfWeek.FRIDAY))
  .atZone(ZoneId.of("PST"));

2. 示例

以下示例将演示如何使用新旧 API 执行常见任务。

获取当前时间

// Old
Date now = new Date();

// New
ZonedDateTime now = ZonedDateTime.now();

表示特定时间

// Old
Date birthDay = new GregorianCalendar(1990, Calendar.DECEMBER, 15).getTime();

// New
LocalDate birthDay = LocalDate.of(1990, Month.DECEMBER, 15);

提取特定字段

// Old
int month = new GregorianCalendar().get(Calendar.MONTH);

// New
Month month = LocalDateTime.now().getMonth();

加减时间

// Old
GregorianCalendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR_OF_DAY, -5);
Date fiveHoursBefore = calendar.getTime();

// New
LocalDateTime fiveHoursBefore = LocalDateTime.now().minusHours(5);

更改特定字段

// Old
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(Calendar.MONTH, Calendar.JUNE);
Date inJune = calendar.getTime();

// New
LocalDateTime inJune = LocalDateTime.now().withMonth(Month.JUNE.getValue());

截断

截断将重置所有小于指定字段的时间字段。在下面的示例中,分钟和以下所有内容都将设置为零

// Old
Calendar now = Calendar.getInstance();
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
Date truncated = now.getTime();

// New
LocalTime truncated = LocalTime.now().truncatedTo(ChronoUnit.HOURS);

时区转换

// Old
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTimeZone(TimeZone.getTimeZone("CET"));
Date centralEastern = calendar.getTime();

// New
ZonedDateTime centralEastern = LocalDateTime.now().atZone(ZoneId.of("CET"));

获取两个时间点之间的时间跨度

// Old
GregorianCalendar calendar = new GregorianCalendar();
Date now = new Date();
calendar.add(Calendar.HOUR, 1);
Date hourLater = calendar.getTime();
long elapsed = hourLater.getTime() - now.getTime();

// New
LocalDateTime now = LocalDateTime.now();
LocalDateTime hourLater = LocalDateTime.now().plusHours(1);
Duration span = Duration.between(now, hourLater);

时间格式化和解析

DateTimeFormatter 是旧的 SimpleDateFormat 的替代品,它是线程安全的并提供附加功能。

// Old
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date now = new Date();
String formattedDate = dateFormat.format(now);
Date parsedDate = dateFormat.parse(formattedDate);

// New
LocalDate now = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDate = now.format(formatter);
LocalDate parsedDate = LocalDate.parse(formattedDate, formatter);

一个月中的天数

// Old
Calendar calendar = new GregorianCalendar(1990, Calendar.FEBRUARY, 20);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

// New
int daysInMonth = YearMonth.of(1990, 2).lengthOfMonth();

3. 与遗留代码交互

在许多情况下,用户可能需要确保与依赖于旧日期库的第三方库的互操作性。

在 Java 8 中,旧的日期库类已经扩展为从新日期 API 将它们转换为相应对象的方法。
新类提供类似的功能。

Instant instantFromCalendar = GregorianCalendar.getInstance().toInstant();
ZonedDateTime zonedDateTimeFromCalendar = new GregorianCalendar().toZonedDateTime();
Date dateFromInstant = Date.from(Instant.now());
GregorianCalendar calendarFromZonedDateTime = GregorianCalendar.from(ZonedDateTime.now());
Instant instantFromDate = new Date().toInstant();
ZoneId zoneIdFromTimeZone = TimeZone.getTimeZone("PST").toZoneId();

4. 结论

在本文中,我们探讨了 Java 8 中可用的新日期时间 API。与已弃用的 API 相比,我们查看了它的优势,并使用多个示例指出了差异。

请注意,我们几乎没有触及新日期时间 API 功能的表面。请务必通读官方文档,以发现新 API 提供的所有工具。

代码示例可以在GitHub 项目中找到。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值