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
---
