/**
* 计算当前日期与指定日期差几个月
* @param date 指定日期 格式:2022-09-07
* @return
*/
public static int theDifferenceBetweenTheMonths(String date){
// 当前日期
LocalDate currentDate = LocalDate.now();
// 给定日期
LocalDate fixedDate = LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE);
// 计算年份和月份的差异
Period period = Period.between(fixedDate, currentDate);
int yearDiff = period.getYears();
int monthDiff = period.getMonths();
// 如果当前日期在给定日期之前,差异值为负数,需要加上一个年份的差异
if (currentDate.isBefore(fixedDate)) {
yearDiff = yearDiff - 1;
}
// 计算总的月份差异
int totalMonthDiff = yearDiff * 12 + monthDiff;
return totalMonthDiff;
}
}
java—计算当前日期与指定日期差几个月
最新推荐文章于 2024-08-01 15:05:06 发布