JS date calculation

Transfer from: JS date addition and subtraction, date calculation

Note: It has been verified by date conversion (28th of a certain month/31st of a certain month), you can eat with confidence

1. The date plus the number of days

//日期加上天数后的新日期.
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;
}

Use: console.log(this.addDays("2021-1-10",40));
Result: 2021-02-19
Use: console.log(this.addDays("2021-2-10",20)) ;
Result: 2021-03-02

2. The date minus the number of days

//日期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;
    }
}

Use: console.log(this.DateDiff("2021-1-21","2020-12-20"));
Result: 32
Use: console.log(this.DateDiff("2021-2-21"," 2021-2-20”));
Result: 1

3. Add or subtract month

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

Guess you like

Origin blog.csdn.net/weixin_46099269/article/details/112916690