方法1
//获取两个日期间的月份和天数,入参为日期格式参数
function getMonthAndDay(startdate, enddate) {
if (startdate.valueOf() > enddate.valueOf()) {
var tmpdt = enddate;
enddate = startdate;
startdate = tmpdt;
}
var month = 0;
var day = 0;
enddate = getNextDay(enddate);
if (enddate.getTime() >= startdate.getTime()) {
month = (enddate.getFullYear() - startdate.getFullYear()) * 12 + enddate.getMonth() - startdate.getMonth();
day = enddate.getDate() - startdate.getDate();
if (day < 0) {
var lastmonthdaynum = getlastmonthDay(enddate);
day += lastmonthdaynum;
if (lastmonthdaynum < 30 && startdate.getDate() > 28) {
day += startdate.getDate() - lastmonthdaynum - 1;
}
month--;
}
} else {
if (startdate.getTime() == getlastDay(startdate)) {
if (enddate.getTime() == getlastDay(enddate)) {
month = enddate.getFullYear() - startdate.getFullYear() * 12 + enddate.getMonth() - startdate.getMonth();
day = 0;
} else {
month = enddate.getFullYear() - startdate.getFullYear() * 12 + enddate.getMonth() - startdate.getMonth() - 1;
day = startdate.getDate();
}
} else {
if (enddate.getTime() == getlastDay(enddate)) {
month = enddate.getFullYear() - startdate.getFullYear() * 12 + enddate.getMonth() - startdate.getMonth();
day = 0;
} else {
month = enddate.getFullYear() - startdate.getFullYear() * 12 + enddate.getMonth() - startdate.getMonth() - 1;
var lastmonthday = getlastmonthDay(enddate);
day = lastmonthday - startdate.getDate() + enddate.getDate();
}
}
}
return { "month": month, "day": day };
}
//得到上一个月有多少天
function getlastmonthDay(date) {
date.setDate(1);
date.setDate(date.getDate() - 1);
return date.getDate();
}
//获取指定日期的后一天日期
function getNextDay(d) {
d = new Date(d);
d = +d + 1000 * 60 * 60 * 24;
d = new Date(d);
var res = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
return new Date(res);
}
//获取 date 所在的月有多少天
function getlastDay(date) {
date.setMonth(date.getMonth() + 1);
date.setDate(1);
date.setDate(date.getDate() - 1);
return date.getDate();
}
// 调用
var startDate = '2021-12-01'
var endDate = '2022-12-01'
var month_day = getMonthAndDay(new Date(startDate), new Date(endDate));
console.log(month_day);//输出结果
方法2
function getMonthsAndDaysBetween(date1, date2) {
var months = date2.getMonth() - date1.getMonth();
if (months < 0) {
months += 12;
}
var days = date2.getDate() - date1.getDate();
return {months: months, days: days};
}
var date1 = new Date("2023-01-01");
var date2 = new Date("2023-06-10");
console.log(getMonthsAndDaysBetween(date1, date2)); // 输出: { months: 5, days: 9 }
// 这个函数首先计算两个日期之间的月份差(这可能为负值,如果第二个日期在第一个日期之前),然后计算天数差。请注意,这个函数假设一个月的长度是固定的(30天),因此可能对于更复杂的情况(例如,考虑闰年和每个月的实际天数)并不准确。如果你需要更精确的解决方案,可能需要使用更复杂的日期计算库,如moment.js。