转载自:https://www.ripjava.com/article/1294911926173728
叙述
在这篇快速的文章中,我们将探讨Java中计算两个日期之间差值的一些方法。
解决方案
使用 java.util.Date
让我们首先使用Java SE API计算两个日期之间的天数:
@Test
public void test_TwoDatesDiffBeforeJava8()
throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH);
Date firstDate = sdf.parse("2019/07/24");
Date secondDate = sdf.parse("2019/07/30");
long diffInMillis = Math.abs(secondDate.getTime() - firstDate.getTime());
long diff = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);
assertEquals(diff, 6);
}
使用Period和Duration
Java 8之后,我们可以使用LocalDate,LocalDateTime来表示两个日期(有或没有时间), 然后使用Period,Duration来计算差值:
使用LocalDate:
@Test
public void test_TwoDatesDiffInJava8() {
LocalDate now = LocalDate.now();
LocalDate sixDaysBehind = now.minusDays(6);
Period period = Period.between(now, sixDaysBehind);
int diff = Math.abs(period.getDays());
assertEquals(diff, 6);
}
使用LocalDateTime:
@Test
public void test_TwoDateTimesInJava8() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime sixMinutesBehind = now.minusMinutes(6);
Duration duration = Duration.between(now, sixMinutesBehind);
long diff = Math.abs(duration.toMinutes());
assertEquals(diff, 6);
}
使用 java.time.temporal.ChronoUnit的between方法
Java 8中的时间日期 API使用TemporalUnit 接口表示时间的单位。比如天和秒。每个单元都提供了between方法的实现。我们可以也使用特定时间的单位计算两个日期之间的差值。
使用LocalDate:
@Test
public void test_TwoDatesDiffInJava8ByChronoUnit() {
LocalDate now = LocalDate.now();
LocalDate sixDaysAfter = now.plusDays(6);
long diff = ChronoUnit.DAYS.between(now, sixDaysAfter);
assertEquals(diff, 6);
}
使用LocalDateTime:
@Test
public void test_TwoDateTimesInJava8ByChronoUnit() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime tenSecondsLater = now.plusSeconds(10);
long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater);
assertEquals(diff, 10);
}
ChronoUnit 通过实现 TemporalUnit接口提供一组具体的时间单位。使用ChronoUnit时,建议使用静态导入,这样代码可读性会强一些。
import static java.time.temporal.ChronoUnit.SECONDS;
// 比如
long diff = SECONDS.between(now, tenSecondsLater);
我们可以将任意的时间对象Temporal传递给 between 方法。即使是表示不同的时区的ZonedDateTime:
@Test
public void test_TwoZonedDateTimesDiffInJava8() {
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime now = ldt.atZone(ZoneId.of("Asia/Tokyo"));
ZonedDateTime sixMinutesBehind = now
.withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
.minusMinutes(6);
long diff = ChronoUnit.MINUTES.between(sixMinutesBehind, now);
assertEquals(diff, 6);
}
使用 java.time.temporal.Temporal的until()方法
任何Temporal对象,比如 LocalDate或ZonedDateTime,都提供了until方法来计算与指定的另一个时间的差值:
@Test
public void test_TwoZonedDateTimesDiffInJava8ByTemporal() {
LocalDateTime now = LocalDateTime.now();
LocalDateTime tenSecondsLater = now.plusSeconds(10);
long diff = now.until(tenSecondsLater, ChronoUnit.SECONDS);
assertEquals(diff, 10);
}
在本文中,我们演示了几种计算日期(有时间和无时间)之间差值的方法
最后,往常一样,代码可以在Github上找到。