var start_date = '2019-08-21';
var end_date = '2020-09-29';
用法:
var month_day = getMonthAndDay(new Date(start_date), new Date(end_date));
返回:{month:13,day:9}
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();
}