import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class ComputeMonth {
//向下取整
public static int getMonthDiff(String startDate, String endDate) {
int result = 0;
try {
SimpleDateFormat sfd = new SimpleDateFormat("yyyy/MM/dd");
Date start = sfd.parse(startDate);
Date end = sfd.parse(endDate);
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(start);
c2.setTime(end);
int startYear = c1.get(Calendar.YEAR);
int startMonth = c1.get(Calendar.MONTH);
int startDay = c1.get(Calendar.DAY_OF_MONTH);
int endYear = c2.get(Calendar.YEAR);
int endMonth = c2.get(Calendar.MONTH);
int endDay = c2.get(Calendar.DAY_OF_MONTH);
int maxDay = c1.getActualMaximum(Calendar.DAY_OF_MONTH);//获取起始日期所在月的最后一天
int maxEndDay = c2.getActualMaximum(Calendar.DAY_OF_MONTH);//获取结束日期所在月的最后一天
if (startDay == maxDay) {//起始日期是在月末
if (maxEndDay == endDay) {
result = (endYear - startYear) * 12 + endMonth - startMonth;
} else {
result = (endYear - startYear) * 12 + endMonth - startMonth - 1;
}
} else if (endDay == maxEndDay) {//结束日期是在月末
result = (endYear - startYear) * 12 + endMonth - startMonth;
} else {
if (endDay >= startDay) {
result = (endYear - startYear) * 12 + endMonth - startMonth;
} else {
result = (endYear - startYear) * 12 + endMonth - startMonth - 1;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
//支持2019/08/30和2019/-08-30两种格式
public static int getMonthsByNow(String startDate){
startDate = startDate.replace("-","/");
String nowDate = new SimpleDateFormat("yyy/MM/dd").format(new Date());
int months = 0;
months = getMonthDiff(startDate,nowDate);//11
return months;
}
public static void main(String[] args) {
int months = getMonthsByNow("2018/09/17");
System.out.println(months);
}
}