JS的日期计算

转自:JS日期加减,日期运算

注:已经过日期换算验证(某月28日/某月31日),可放心食用

1、日期加上天数

//日期加上天数后的新日期.
addDays(date,days){
    
    
    var nd = new Date(date);
    nd = nd.valueOf();
    nd = nd + days * 24 * 60 * 60 * 1000;
    nd = new Date(nd);
    //alert(nd.getFullYear() + "年" + (nd.getMonth() + 1) + "月" + nd.getDate() + "日");
    var y = nd.getFullYear();
    var m = nd.getMonth()+1;
    var d = nd.getDate();
    if(m <= 9) m = "0"+m;
    if(d <= 9) d = "0"+d; 
    var cdate = y+"-"+m+"-"+d;
    return cdate;
}

使用:console.log(this.addDays(“2021-1-10”,40));
结果:2021-02-19
使用:console.log(this.addDays(“2021-2-10”,20));
结果:2021-03-02

2、日期减去天数

//日期1减去日期2的天数.
dateDiff(d1,d2){
    
    
    var day = 24 * 60 * 60 *1000;
    try{
    
        
        var dateArr = d1.split("-");
        var checkDate = new Date();
        checkDate.setFullYear(dateArr[0], dateArr[1]-1, dateArr[2]);
        var checkTime = checkDate.getTime();

        var dateArr2 = d2.split("-");
        var checkDate2 = new Date();
        checkDate2.setFullYear(dateArr2[0], dateArr2[1]-1, dateArr2[2]);
        var checkTime2 = checkDate2.getTime();

        var cha = (checkTime - checkTime2)/day;  
        return cha;
    }catch(e){
    
    
        return false;
    }
}

使用:console.log(this.DateDiff(“2021-1-21”,“2020-12-20”));
结果:32
使用:console.log(this.DateDiff(“2021-2-21”,“2021-2-20”));
结果:1

3、加减月份

var d = new Date()
d.setMonth(d.getMonth()+1);

猜你喜欢

转载自blog.csdn.net/weixin_46099269/article/details/112916690
今日推荐