话不多说直接上代码
// num为过去或未来日子的标准;例('-30')为当前日期前30天,('30')为当前日期后30天
function beforeDate (num, dateParameter) {
var translateDate = ''
var dateString = ''
var monthString = ''
var dayString = ''
translateDate = dateParameter
var newDate = new Date(translateDate)
newDate = newDate.valueOf()
if (num.indexOf('-') === -1) { // 判断日期加减方式
newDate = newDate + num * 24 * 60 * 60 * 1000 // 如果是往后计算日期则为加号
} else {
let numList = num.split('-')
num = numList[1]
newDate = newDate - num * 24 * 60 * 60 * 1000 // 如果是往前计算日期则为减号
}
newDate = new Date(newDate)
// 如果月份长度少于2,则前加 0 补位
if ((newDate.getMonth() + 1).toString().length == 1) {
monthString = 0 + '' + (newDate.getMonth() + 1).toString()
} else {
monthString = (newDate.getMonth() + 1).toString()
}
// 如果天数长度少于2,则前加 0 补位
if (newDate.getDate().toString().length == 1) {
dayString = 0 + '' + newDate.getDate().toString()
} else {
dayString = newDate.getDate().toString()
}
dateString = newDate.getFullYear() + '-' + monthString + '-' + dayString
console.log(dateString)
}