获取当前日期的前n天或者后n天的日期

这里的n指的是距离当前日期多少天

1.获取当前日期的前n天的日期

function getPreDate(n) {
    let date =  new Date(new Date().getTime()- n * 24 * 60* 60 * 1000);
    let year = date.getFullYear(); 
    //返回的是月份 记得+1 才是当前月 (从0开始 0代表1月)  
    let month1 = date.getMonth() + 1; 
    let month = month1 < 10 ? "0" + month1 : month1;
    let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    let startDate = year.toString()+'/' + month.toString()+'/' +day.toString();
    return startDate;
}

2.获取当前日期的后n天的日期

function getLaterDate(n) {
    let date =  new Date(new Date().getTime()+ n * 24 * 60* 60 * 1000);
    let year = date.getFullYear();
    let month1 = date.getMonth() + 1; 
    let month = month1 < 10 ? "0" + month1 : month1;
    let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    let startDate = year.toString()+'/' + month.toString()+'/' +day.toString();
    return startDate;
}

你可能感兴趣的:(前端,JavaScript,Vue,前端,javascript,vue)