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

我曾經遇到這個問題:給定兩個JavaScript的Date對象,我該如何獲取這兩個日期之間的日期(也表示為Date對象)列表?

這裡有一個用於計算日期的函數:

它以兩個日期對象作為參數,並返回一個日期對象的數組:

const getDatesBetweenDates = (startDate, endDate) => {
  let dates = []
  // 為了避免修改原始日期
  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 = []
  // 為了避免修改原始日期
  const theDate = new Date(startDate)
  while (theDate < endDate) {
    dates = [...dates, new Date(theDate)]
    theDate.setDate(theDate.getDate() + 1)
  }
  dates = [...dates, endDate]
  return dates
}