JS Gets the date a few days before and after the date apart

JS acquisition date separated by a few days before and after the specified date.

/**
*date为开始日期,dayLength是相隔的天数,可以为负数;(可跨年)
*/
function getTargetDate(date,dayLength) {
    var tempDate = new Date(date);
    tempDate.setDate(tempDate.getDate() + dayLength);
    var year = tempDate.getFullYear();
    var month = tempDate.getMonth() + 1 < 10 ? "0" + (tempDate.getMonth() + 1) : tempDate.getMonth() + 1;
    var day = tempDate.getDate() < 10 ? "0" + tempDate.getDate() : tempDate.getDate();
    return year + "-" + month + "-" + day;
}

Test: getTargetDate (new Date ( "2019-12-31 "), 1);
Results: 2020-01-01

Published 37 original articles · won praise 29 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_42755868/article/details/91888695
Recommended