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

---

相关文章:

  • 2021-10-03
  • 2021-11-06
  • 2022-02-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-03
  • 2021-09-23
  • 2021-12-30
  • 2021-11-11
相关资源
相似解决方案