JavaScript日期加减

  JavaScript日期加减

var date = new Date()

// 对日期加减:
date.setDate(date.getDate() + n)

// 对月加减:
date.setMonth(date.getMonth() + n)

// 对年加减:
date.setFullYear(date.getFullYear() + n)

  测试:

function convertDate2String(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()

    let time = year
    if (month < 10) time += "0"
    time += month
    if (day < 10) time += "0"
    time += day
    return time
}

let date = new Date()
console.log(convertDate2String(date)) // 20200120

//date.setDate(date.getDate() + 10)
//console.log(convertDate2String(date)) // 20200130
// 加减的时候跨越了月、年,那么JS的date类型会自动的处理跨越问题
date.setDate(date.getDate() + 12)
console.log(convertDate2String(date)) // 20200201

---

猜你喜欢

转载自www.cnblogs.com/xy-ouyang/p/12217167.html