如何计算两个时间的月份差(包括跨年)
/**
* 获取两个日期相差的月数
*/
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;
}
测试:
public static void main(String[] args) throws Exception {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-DD");
Date d1 = simpleDateFormat.parse("2019-12-18");
Date d2 = simpleDateFormat.parse("2020-12-17");
System.out.println("时间相差月份是:"+getMonthDiff(d1, d2));
}
控制台:

测试成功

本文介绍了一种计算两个日期之间月份数的方法,包括跨年情况,通过使用Java的Calendar类和数学运算实现。提供了详细的代码示例和测试案例。
1084

被折叠的 条评论
为什么被折叠?



