JS Jquery 根据两个日期计算相差月数天数 兼容二月份28天29天

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();
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值