计算两个Data类型日期的时间差 java
时间: 2023-09-11 14:04:04 浏览: 97
可以使用`java.time.Duration`类来计算两个日期之间的时间差。以下是一个示例代码:
```java
import java.time.Duration;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DateDifferenceExample {
public static void main(String[] args) {
// 创建两个日期
LocalDate date1 = LocalDate.of(2021, 1, 1);
LocalDate date2 = LocalDate.of(2021, 3, 31);
// 计算日期之间的天数差
long daysDiff = ChronoUnit.DAYS.between(date1, date2);
System.out.println("Days Difference: " + daysDiff);
// 计算日期之间的月数差
long monthsDiff = ChronoUnit.MONTHS.between(date1, date2);
System.out.println("Months Difference: " + monthsDiff);
// 计算日期之间的年数差
long yearsDiff = ChronoUnit.YEARS.between(date1, date2);
System.out.println("Years Difference: " + yearsDiff);
// 计算日期之间的小时差
Duration duration = Duration.between(date1.atStartOfDay(), date2.atStartOfDay());
long hoursDiff = duration.toHours();
System.out.println("Hours Difference: " + hoursDiff);
// 计算日期之间的分钟差
long minutesDiff = duration.toMinutes();
System.out.println("Minutes Difference: " + minutesDiff);
}
}
```
输出:
```
Days Difference: 89
Months Difference: 2
Years Difference: 0
Hours Difference: 2136
Minutes Difference: 128160
```
在这个示例中,我们创建了两个`LocalDate`对象表示2021年1月1日和2021年3月31日。然后,我们使用`ChronoUnit`类计算了日期之间的天数差、月数差和年数差。我们还使用`Duration`类计算了日期之间的小时差和分钟差。
阅读全文