如何在JavaScript中获得两个日期之间的天数

44 阅读1分钟

给定两个JavaScript `Date`对象,我怎样才能得到这两个日期之间的天数列表(也表示为Date对象)?

我有这样的问题:给定两个JavaScriptDate 对象,我怎样才能得到这两个日期之间的日期列表(也表示为Date对象)?

这里有一个函数来计算这个问题。

它得到两个日期对象作为参数,并返回一个日期对象的数组。

const getDatesBetweenDates = (startDate, endDate) => {
  let dates = []
  //to avoid modifying the original date
  const theDate = new Date(startDate)
  while (theDate < endDate) {
    dates = [...dates, new Date(theDate)]
    theDate.setDate(theDate.getDate() + 1)
  }
  return dates
}

使用实例。

const today = new Date()
const threedaysFromNow = new Date(today)
threedaysFromNow.setDate( threedaysFromNow.getDate() + 3)

getDatesBetweenDates(today, threedaysFromNow)

如果你还想包括开始和结束的日期,你可以使用这个版本,在最后加上它。

const getDatesBetweenDates = (startDate, endDate) => {
  let dates = []
  //to avoid modifying the original date
  const theDate = new Date(startDate)
  while (theDate < endDate) {
    dates = [...dates, new Date(theDate)]
    theDate.setDate(theDate.getDate() + 1)
  }
  dates = [...dates, endDate]
  return dates
}