通过日历对象计算两个日期相差多少个月
package com.cmft.marathon.dto;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String startDate = "2021-04-10";
String endDate = "2020-11-04";
Date start = sdf.parse(startDate);
Date end = sdf.parse(endDate);
Integer difMonth = getMonth(start, end);
System.out.println("相差的月份是:" + difMonth);
}
public static Integer getMonth(Date startDate, Date endDate) {
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.setTime(startDate);
end.setTime(endDate);
int month = end.get(Calendar.MONTH) - start.get(Calendar.MONTH);
int months = (end.get(Calendar.YEAR) - start.get(Calendar.YEAR)) * 12;
return Math.abs(month + months);
}
}