Home 计算相差的月数
Post
Cancel

计算相差的月数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public static int getMonthDiff(Date d1, Date d2) {
	Calendar c1 = Calendar.getInstance();
	Calendar c2 = Calendar.getInstance();
	c1.setTime(d1);
	c2.setTime(d2);
	int year1 = c1.get(Calendar.YEAR);
	int year2 = c2.get(Calendar.YEAR);
	int month1 = c1.get(Calendar.MONTH);
	int month2 = c2.get(Calendar.MONTH);
	int day1 = c1.get(Calendar.DAY_OF_MONTH);
	int day2 = c2.get(Calendar.DAY_OF_MONTH);
	// 获取年的差值
	int yearInterval = year1 - year2;
	// 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数
	if (month1 < month2 || month1 == month2 && day1 < day2) {
		yearInterval--;
	}
	// 获取月数差值
	int monthInterval = (month1 + 12) - month2;
	if (day1 < day2) {
		monthInterval--;
	}
	monthInterval %= 12;
	int monthsDiff = Math.abs(yearInterval * 12 + monthInterval);
	return monthsDiff;
}
This post is licensed under CC BY 4.0 by the author.