Java如何计算两个日期之间的差异?
在此示例中,您将学习如何使用java.time.Period该类(来自Java 8)来计算两个日期之间的差异。使用Period.between()方法将使我们可以区分年,月和日期间的两个日期。
除了使用Period该类外,我们还使用ChronoUnit枚举来计算两个日期之间的差。我们使用和ChronoUnit.YEARS,ChronoUnit.MONTHS并ChronoUnit.DAYS调用between()方法以获取年,月和日中两个日期之间的差。
让我们看下面的例子。
package org.nhooo.example.datetime;import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class DateDifference {
public static void main(String[] args) {
LocalDate birthDate = LocalDate.of(1995, Month.AUGUST, 17);
LocalDate now = LocalDate.now();
// 获得一个由年,月和天数组成的期间
// 在两个日期之间。
Period age = Period.between(birthDate, now);
System.out.printf("You are now %d years, %d months and %d days old.%n",
age.getYears(), age.getMonths(), age.getDays());
// 使用ChronoUnit计算年,月和日的差异
// 在两个日期之间。
long years = ChronoUnit.YEARS.between(birthDate, now);
long months = ChronoUnit.MONTHS.between(birthDate, now);
long days = ChronoUnit.DAYS.between(birthDate, now);
System.out.println("Diff in years = " + years);
System.out.println("Diff in months = " + months);
System.out.println("Diff in days = " + days);
}
}
上面我们的代码片段的结果是:
You are now 20 years, 5 months and 5 days old.Diff in years = 20
Diff in months = 245
Diff in days = 7463
以上是 Java如何计算两个日期之间的差异? 的全部内容, 来源链接: utcz.com/z/354916.html