这是从网上复制的 不知道对不对
最好能解释下months_between(函数)的源码是怎么操作的
public class Months_between {
/**
* 计算两个日期相差的月份数
*
* @param date1 日期1
* @param date2 日期2
* @param pattern 日期1和日期2的日期格式
* @return 相差的月份数
* @throws
*/
private Date date1;
private Date date2;
public static int countMonths(String date1, String date2, String pattern) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(sdf.parse(date1));
c2.setTime(sdf.parse(date2));
int year = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
/*//开始日期若小月结束日期
if (year < 0) {
year = -year;
return year * 12 + c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
}*/
return year * 12 + c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
}
}
因为是两个日期差,所以可能第一个大,也可能第二个大,所以if (year < 0) 后需要颠倒下
year * 12 + c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
颠倒下就是
-year * 12 - c2.get(Calendar.MONTH) + c1.get(Calendar.MONTH);
也就是
return -year * 12 + c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
也就是
year = -year;
return year * 12 + c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
计算两个月差多少个月。
思路是
int year = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
先算出差多少整年,year * 12
再加上头尾差多少个月c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
比如2016年8月到2018年4月
那么year=2
月份相差是-4
结果就是2*12+(-4)=20个月
假设c1是2018-4-25
c1.get(Calendar.MONTH) 返回4
c1.get(Calendar.YEAR) 返回 2018