這是從網(wǎng)上復(fù)制的 不知道對不對 最好能解釋下months_between(函數(shù))的源碼是怎么操作的 public class Months_between {/**
* 計算兩個日期相差的月份數(shù)
*
* @param date1 日期1
* @param date2 日期2
* @param pattern 日期1和日期2的日期格式
* @return 相差的月份數(shù)
* @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);
/*//開始日期若小月結(jié)束日期
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貢獻(xiàn)1824條經(jīng)驗 獲得超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
提交
取消