var range = getDates(new Date(), new Date().addDays(7));
I\'d like \"range\" to be an array of date objects, one for each day between the two dates
I'm using simple while loop to calculate the between dates
var start = new Date("01/05/2017");
var end = new Date("06/30/2017");
var newend = end.setDate(end.getDate()+1);
end = new Date(newend);
while(start < end){
console.log(new Date(start).getTime() / 1000); // unix timestamp format
console.log(start); // ISO Date format
var newDate = start.setDate(start.getDate() + 1);
start = new Date(newDate);
}
I use moment.js and Twix.js they provide a very great support for date and time manpulation
var itr = moment.twix(new Date('2012-01-15'),new Date('2012-01-20')).iterate("days");
var range=[];
while(itr.hasNext()){
range.push(itr.next().toDate())
}
console.log(range);
I have this running on http://jsfiddle.net/Lkzg1bxb/
Just came across this question, the easiest way to do this is using moment:
You need to install moment and moment-range first:
const Moment = require('moment');
const MomentRange = require('moment-range');
const moment = MomentRange.extendMoment(Moment);
const start = moment()
const end = moment().add(2, 'months')
const range = moment.range(start, end)
const arrayOfDates = Array.from(range.by('days'))
console.log(arrayOfDates)
This is how i like to do it
// hours * minutes * seconds * milliseconds
const DAY_IN_MS = 24 * 60 * 60 * 1000
/**
* Get range of dates
* @param {Date} startDate
* @param {Number} numOfDays
* @returns {array}
*/
const dateRange = (startDate, numOfDays) => {
const startDateMs = startDate.getTime()
// get array of days and map it to Date object
return [...Array(numOfDays).keys()].map(i => new Date(startDateMs + i * DAY_IN_MS))
}
I use this function
function getDatesRange(startDate, stopDate) {
const ONE_DAY = 24*3600*1000;
var days= [];
var currentDate = new Date(startDate);
while (currentDate <= stopDate) {
days.push(new Date (currentDate));
currentDate = currentDate - 1 + 1 + ONE_DAY;
}
return days;
}
I was recently working with moment.js, following did the trick..
function getDateRange(startDate, endDate, dateFormat) {
var dates = [],
end = moment(endDate),
diff = endDate.diff(startDate, 'days');
if(!startDate.isValid() || !endDate.isValid() || diff <= 0) {
return;
}
for(var i = 0; i < diff; i++) {
dates.push(end.subtract(1,'d').format(dateFormat));
}
return dates;
};
console.log(getDateRange(startDate, endDate, dateFormat));
Result would be:
["09/03/2015", "10/03/2015", "11/03/2015", "12/03/2015", "13/03/2015", "14/03/2015", "15/03/2015", "16/03/2015", "17/03/2015", "18/03/2015"]