1.借助hutool工具类
//引入包
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.10</version>
</dependency>
2.代码实现
String text1 = "2019-03-25";
Temporal startDate = LocalDate.parse(text1);
String text2 = "2022-05-30";
Temporal endDate = LocalDate.parse(text2);
//方法返回为相差年数
long year = ChronoUnit.YEAR.between(startDate, endDate);
System.out.println(year);
// 方法返回为相差月数
long month = ChronoUnit.MONTHS.between(startDate, endDate);
System.out.println(month);
//方法返回为相差天数
long day = ChronoUnit.DAYS.between(startDate, endDate);
System.out.println(day);
3.Date格式时间计算
Date startDate = new Date(1553443200000L);
Date endDate = new Date(System.currentTimeMillis());
long betweenMonth = DateUtil.betweenMonth(startDate, endDate, true);
System.out.println(betweenMonth);