java 获取两个日期差_java如何获取两个日期的时间差
时间: 2023-07-18 18:05:14 浏览: 104
获取指定两个日期之间的所以日期
在 Java 中,可以使用 `java.time` 包中的 `LocalDate` 类来计算两个日期之间的差值。以下是一个示例代码:
```java
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DateDifference {
public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2021, 1, 1);
LocalDate date2 = LocalDate.of(2021, 3, 15);
long daysBetween = ChronoUnit.DAYS.between(date1, date2);
System.out.println("Days between " + date1 + " and " + date2 + ": " + daysBetween);
long monthsBetween = ChronoUnit.MONTHS.between(date1, date2);
System.out.println("Months between " + date1 + " and " + date2 + ": " + monthsBetween);
long yearsBetween = ChronoUnit.YEARS.between(date1, date2);
System.out.println("Years between " + date1 + " and " + date2 + ": " + yearsBetween);
}
}
```
在这个示例中,我们创建了两个 `LocalDate` 对象,然后使用 `ChronoUnit` 枚举类中的 `DAYS`、`MONTHS` 和 `YEARS` 常量来计算它们之间的差值。最后输出结果。
你也可以使用 `Period` 类来计算两个日期之间的差值,如下所示:
```java
import java.time.LocalDate;
import java.time.Period;
public class DateDifference {
public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2021, 1, 1);
LocalDate date2 = LocalDate.of(2021, 3, 15);
Period period = Period.between(date1, date2);
System.out.println("Days between " + date1 + " and " + date2 + ": " + period.getDays());
System.out.println("Months between " + date1 + " and " + date2 + ": " + period.getMonths());
System.out.println("Years between " + date1 + " and " + date2 + ": " + period.getYears());
}
}
```
在这个示例中,我们使用 `Period` 类来计算两个日期之间的差值,并输出结果。`Period` 类提供了各种方法来获取差值的年、月、日等部分。
阅读全文