Java 8 - 日期比较

2017/11/30 posted in  Java 8

在这篇文章中,我将列举一些方法来计算两个日期之间的差值。第一个方法是使用 Jodatime API 进行计算,这个 API 即使在 java 8 发布之前也是可用的。后面的方法是使用 java 8 新的 Date Time API。

使用 JodaTime 计算两个日期之间的差值(java 8 之前)

由于你们都喜欢可读性,所以我会建议使用 Jodatime library(java 8 的 date/time APIs 也是受此启发)。

public void difference_between_two_dates_duration_Joda()
 {
     DateTime dateOfBirth = new DateTime(1988, 7, 4, 0, 0, GregorianChronology.getInstance());
     DateTime currentDate = new DateTime();
     Days diffInDays = Days.daysBetween(dateOfBirth, currentDate);
     Hours diffInHours = Hours.hoursBetween(dateOfBirth, currentDate);
     Minutes diffInMinutes = Minutes.minutesBetween(dateOfBirth, currentDate);
     Seconds seconds = Seconds.secondsBetween(dateOfBirth, currentDate);
 }

Java 8 计算两个日期之间的差值

Java Dates 一直缺乏足够的支持来有效地表达日期和时间段。Java 8 首次尝试升级了这个 date/time API。如果在你的项目中使用了 java 8,那无疑可以使用以下给出的任何一种方法来计算两个日期之间的差值。

使用 java.time.Period 来获取 天/月/年 的差值

LocalDate endofCentury = LocalDate.of(2014, 01, 01);
LocalDate now = LocalDate.now();
 
Period diff = Period.between(endofCentury, now);
 
System.out.printf("Difference is %d years, %d months and %d days old",
                    diff.getYears(), diff.getMonths(), diff.getDays());

使用 java.time.temporal.ChronoUnit 来获取 天/月/年 的差值

public void difference_between_two_dates_java8()
{
     LocalDate dateOfBirth = LocalDate.of(1980, Month.JULY, 4);
     LocalDate currentDate = LocalDate.now();
     long diffInDays = ChronoUnit.DAYS.between(dateOfBirth, currentDate);
     long diffInMonths = ChronoUnit.MONTHS.between(dateOfBirth, currentDate);
     long diffInYears = ChronoUnit.YEARS.between(dateOfBirth, currentDate);
}

你也可以使用 ChronoUnit 来获取更小的时间单位,比如,毫秒,分钟,等等。但是在这种情况下,你就得把第一个示例中的 LocalDate 改为 LocalDateTime

public void difference_between_two_dates_duration()
 {
     LocalDateTime dateTime = LocalDateTime.of(1988, 7, 4, 0, 0);
     LocalDateTime dateTime2 = LocalDateTime.now();
     long diffInNano = ChronoUnit.NANOS.between(dateTime, dateTime2);
     long diffInSeconds = ChronoUnit.SECONDS.between(dateTime, dateTime2);
     long diffInMilli = ChronoUnit.MILLIS.between(dateTime, dateTime2);
     long diffInMinutes = ChronoUnit.MINUTES.between(dateTime, dateTime2);
     long diffInHours = ChronoUnit.HOURS.between(dateTime, dateTime2);
 }

使用 java.time.Duration 来获取 毫秒/秒/分 的差值

public void difference_between_two_dates_duration()
 {
     LocalDateTime dateTime = LocalDateTime.of(1988, 7, 4, 0, 0);
     LocalDateTime dateTime2 = LocalDateTime.now();
    int diffInNano = java.time.Duration.between(dateTime, dateTime2).getNano();
     long diffInSeconds = java.time.Duration.between(dateTime, dateTime2).getSeconds();
     long diffInMilli = java.time.Duration.between(dateTime, dateTime2).toMillis();
     long diffInMinutes = java.time.Duration.between(dateTime, dateTime2).toMinutes();
     long diffInHours = java.time.Duration.between(dateTime, dateTime2).toHours();
 }

以上3个方法拥有足够的可读性以及灵活性来获取两个日期之间的多个时间单元的差值。

参考资料