思君如明烛,煎心且衔泪。
概述
Java示例,使用Java 8计算中两个日期之间的差异。首先,我们将学习使用Jodatime API来计算,该API在Java 8发布之前就已经可用了。如果您仍然不习惯使用Java 8,那么JodaTime应该是你的首选。
JodaTime 两个日期时间之差
MAVEN
joda-time joda-time 2.10
示例
由于大家都喜欢喜欢性,建议使用Jodatime库(它实际上启发了 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 Date一直缺乏足够的支持来有效地表达日期和时间段。Java 8首次尝试升级此date/time API。如果你在项目中使用的是Java 8,则一定要使用以下两种方法之一来计算两个日期之间的日期/时间差。
java.time.Period示例,计算天/月/年的时间差
可使用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示例,计算天/月/年的差
可使用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来计算更小的时间单位,如几分钟,分钟等。但是在这种情况下,你必须使用LocalDateTime来代替第一个示例中使用的LocalDate。
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示例,计算毫米/秒/分钟等的差
可使用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(); }
以上三种方法都具有足够的初步性和重要性,可以知道不同时间单位的日期之间的差异。
译文链接:Java 8两个日期之间的差异