如何在JavaScript中獲取兩個日期之間的天數
給定兩個JavaScript的Date
對象,我該如何獲取這兩個日期之間的日期(也表示為Date對象)列表?
我曾經遇到這個問題:給定兩個JavaScript的Date
對象,我該如何獲取這兩個日期之間的日期(也表示為Date對象)列表?
這裡有一個用於計算日期的函數:
它以兩個日期對象作為參數,並返回一個日期對象的數組:
1 2 3 4 5 6 7 8 9 10
| 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 }
|
使用示例:
1 2 3 4 5
| const today = new Date() const threedaysFromNow = new Date(today) threedaysFromNow.setDate(threedaysFromNow.getDate() + 3)
getDatesBetweenDates(today, threedaysFromNow)
|
如果你還想包括起始日期和結束日期,可以使用下面這個版本,在最後添加它們:
1 2 3 4 5 6 7 8 9 10 11
| 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 }
|
tags: [“JavaScript”, “Date object”, “Array”, “Function”, “Coding技巧”]