js获取当前日期前n天 和 后n天的日期
function getdate(n){
var n = n;
var myDate = new Date();
var year = myDate.getFullYear();
var month = myDate.getMonth() + 1;
var day = myDate.getDate();
if(day <= n) {
if(month > 1) {
month = month - 1;
} else {
year = year - 1;
month = 12;
}
}
myDate.setDate(myDate.getDate() - n);
year = myDate.getFullYear();
month = myDate.getMonth() + 1;
day = myDate.getDate();
appointDate = year + "-" + (month < 10 ? ('0' + month) : month) + "-" + (day < 10 ? ('0' + day) : day);
return appointDate;
}
console.log(getdate('7')) // 2022-03-23
console.log(getdate('10')) // 2022-03-08
console.log(getdate('-7')) // 2022-04-06
console.log(getdate('-10')) // 2022-04-09
⚠️ 当前日期2022-03-30
⚠️ n是正数 前n天的日期
⚠️ n是负数 后n天的日期
网友评论