Last active
February 22, 2025 20:28
-
Star
(108)
You must be signed in to star a gist -
Fork
(27)
You must be signed in to fork a gist
-
-
Save miguelmota/7905510 to your computer and use it in GitHub Desktop.
Get dates in between two dates with JavaScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Returns an array of dates between the two dates | |
function getDates (startDate, endDate) { | |
const dates = [] | |
let currentDate = startDate | |
const addDays = function (days) { | |
const date = new Date(this.valueOf()) | |
date.setDate(date.getDate() + days) | |
return date | |
} | |
while (currentDate <= endDate) { | |
dates.push(currentDate) | |
currentDate = addDays.call(currentDate, 1) | |
} | |
return dates | |
} | |
// Usage | |
const dates = getDates(new Date(2013, 10, 22), new Date(2013, 11, 25)) | |
dates.forEach(function (date) { | |
console.log(date) | |
}) |
This for Get range dates, work for me
var start = '24-01-2022';
var end = '26-01-2022';
var dates = getDates(new Date(start), new Date(end));
// dates.forEach(function(date) {
// console.log(date);
// });
// Get Range Dates
console.log(dates.length);
Life saver. Thank you @miguelmota.
I would convert it to TypeScript version.
const getDates = (startDate: Date, endDate: Date) => {
const dates = []
let currentDate = startDate
const addDays = (currentDate: Date, days: number) => {
const date = new Date(currentDate)
date.setDate(date.getDate() + days)
return date
}
while (currentDate <= endDate) {
dates.push(currentDate)
currentDate = addDays(currentDate, 1)
}
return dates
}
I would convert it to TypeScript version.
const getDates = (startDate: Date, endDate: Date) => { const dates = [] let currentDate = startDate const addDays = (currentDate: Date, days: number) => { const date = new Date(currentDate) date.setDate(date.getDate() + days) return date } while (currentDate <= endDate) { dates.push(currentDate) currentDate = addDays(currentDate, 1) } return dates }
Thank you
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Perfectly.. Thanks u bro