这是从网上复制的 不知道对不对 最好能解释下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);
}}
1 回答

慕妹3242003
TA贡献1824条经验 获得超6个赞
因为是两个日期差,所以可能第一个大,也可能第二个大,所以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);
添加回答
举报
0/150
提交
取消