计算日期间隔自然月份和天数
给定两个时间,startTime和endTime。计算这两个时间的间隔月份数,不是整月计算天数,月份数按照自然月来计算。举几个例子:
startTime:2022-02-16 00:00:00
endTime:2022-06-15 23:59:59
这两个时间间隔4个月。
startTime:2022-02-16 00:00:00
endTime:2022-08-27 23:59:59
这两个时间间隔6个月12天。
startTime:2022-02-16 00:00:00
endTime:2022-02-28 23:59:59
这两个时间间隔13天。
这里要注意,23:59:59相当于第二天的凌晨了。
我将月份数和天数转换为了整数部分和小数部分。比如:12个月20天,转换为:12.20。如果不需要这种格式,可以自己处理。
下面看代码
public double monthInterval(Date startTime,Date endTime){
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startTime);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endTime);
// 23:59:59 算第二天凌晨
startCalendar.add(Calendar.SECOND, 1);
endCalendar.add(Calendar.SECOND, 1);
double finalMathInterval;
// 数据校验
if (startTime.after(endTime)) {
// 错误日期
return -999.9;
}
int startYear = startCalendar.get(Calendar.YEAR);
int endYear = endCalendar.get(Calendar.YEAR);
int startMonth = startCalendar.get(Calendar.MONTH) + 1;
int endMonth = endCalendar.get(Calendar.MONTH) + 1;
int startDay = startCalendar.get(Calendar.DAY_OF_MONTH);
int endDay = endCalendar.get(Calendar.DAY_OF_MONTH);
int diffYear = endYear - startYear;
if (endMonth < startMonth && diffYear != 0) {
diffYear = diffYear - 1;
}
// 天数相等
if (startDay == endDay) {
if (endMonth < startMonth) {
finalMathInterval = 12 - startMonth + endMonth;
} else {
finalMathInterval = diffYear * 12 + endMonth - startMonth;
}
} else {
int diffMonth = endMonth - startMonth;
if (endMonth < startMonth) {
diffMonth = 12 - startMonth + endMonth;
}
if (endDay < startDay) {
diffMonth = diffMonth - 1;
}
int monthInterval = diffYear * 12 + diffMonth;
// 计算相差天数
// 预期月份后的日期
startCalendar.add(Calendar.MONTH, monthInterval);
int actualMaxDay = startCalendar
.getActualMaximum(Calendar.DAY_OF_MONTH);
int expectMonth = startCalendar.get(Calendar.MONTH) + 1;
int diffDay;
double diffDayDouble;
if (expectMonth == endMonth) {
diffDay = endDay - startDay;
} else {
diffDay = actualMaxDay - startDay + endDay;
}
if (diffDay <= 10) {
diffDayDouble = new BigDecimal(diffDay).divide(
new BigDecimal("10"), 1, RoundingMode.HALF_UP)
.doubleValue();
} else {
diffDayDouble = new BigDecimal(diffDay).divide(
new BigDecimal("100"), 2, RoundingMode.HALF_UP)
.doubleValue();
}
finalMathInterval = monthInterval + diffDayDouble;
}
return finalMathInterval;
}
计算日期间隔自然月份和天数
https://www.zhaojun.inkhttps://www.zhaojun.ink/archives/calculate-date-interval