function getFormatDate(type, num) {
let currentDate = new Date();
let resultDate = currentDate;
let formatYMD;
let day = 0,month = 0,year = 0;
if (type === 'y') { // 按年份计算
resultDate = currentDate.setFullYear((currentDate.getFullYear() + num));
} else if (type === 'm') { // 按月份计算
resultDate = currentDate.setMonth((currentDate.getMonth() + num));
} else if (type === 'd') { // 按天计算
resultDate = currentDate.setDate((currentDate.getDate() + num));
} else if (type === 'h') { // 按小时计算
resultDate = currentDate.setHours(currentDate.getHours() + num);
}
year = (new Date(resultDate)).getFullYear();
month = (new Date(resultDate)).getMonth() + 1;
day = (new Date(resultDate)).getDate();
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
formatYMD = year + '-' + month + '-' + day;
return formatYMD;
}
console.log("上一年:",getFormatDate("y", -1));
console.log("下一年:",getFormatDate("y", 1));
console.log("上一月:",getFormatDate("m", -1));
console.log("下一月:",getFormatDate("m", 1));
console.log("上一天:",getFormatDate("d", -1));
console.log("下一天:",getFormatDate("d", 1));
console.log("上一小时:",getFormatDate("h", -1));
console.log("下一小时:",getFormatDate("h", 1));
个人记录,方便查找!