java中实现两个日期相减
时间: 2024-05-11 17:16:54 浏览: 170
javaScript日期相减
在 Java 中可以使用 Java 8 引入的 java.time 包来实现两个日期的相减操作。下面是一个示例代码:
```java
import java.time.Duration;
import java.time.LocalDate;
import java.time.Period;
public class DateSubtraction {
public static void main(String[] args) {
// 创建两个日期
LocalDate date1 = LocalDate.of(2021, 10, 1);
LocalDate date2 = LocalDate.of(2021, 10, 10);
// 计算日期之间的天数差
long days = Duration.between(date1.atStartOfDay(), date2.atStartOfDay()).toDays();
System.out.println("Days between " + date1 + " and " + date2 + ": " + days);
// 计算日期之间的月份差和天数差
Period period = Period.between(date1, date2);
System.out.println("Period between " + date1 + " and " + date2 + ": " + period.getMonths() + " months and " + period.getDays() + " days");
}
}
```
运行以上代码,输出如下:
```
Days between 2021-10-01 and 2021-10-10: 9
Period between 2021-10-01 and 2021-10-10: 0 months and 9 days
```
阅读全文