如何在JavaScript中獲取兩個日期之間的日期

給定兩個JavaScriptDate對象,如何獲取這兩個日期之間的日期列表(也表示為Date對象)?

我有這個問題:給定兩個JavaScriptDate對象,如何獲取這兩個日期之間的日期列表(也表示為Date對象)?

這是一個計算該函數的函數。

它獲取2個date對像作為參數,並返回一個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
}

免費下載我的JavaScript初學者手冊


更多js教程: