309
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.

The trick is that it should handle month and year boundaries as well.

1
  • 1
    If date-fns is allowed to use, eachDayOfInterval 1 and addDays 2 are what can be used to return an array of dates between start date and end date. Commented Dec 10, 2022 at 12:52

34 Answers 34

252
Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

function getDates(startDate, stopDate) {
    var dateArray = new Array();
    var currentDate = startDate;
    while (currentDate <= stopDate) {
        dateArray.push(new Date (currentDate));
        currentDate = currentDate.addDays(1);
    }
    return dateArray;
}

Here is a functional demo http://jsfiddle.net/jfhartsock/cM3ZU/

Sign up to request clarification or add additional context in comments.

12 Comments

Thanks John. I mostly used yours, but you have a byRef bug, in that currentDate can't get pushed onto the array or you'll end up with an array of n elements, all as the last date. Changing it to currentDate = new Date(currentDate) works.
this is fine for the future date,But when I am working on past date like 30 days before where should i change the above code to get only date not time.
@vaibhavkulkarni You can simply reverse the addays() prototype and modify the while loop. In addition, comments are not the place to start up a new question.
Should we better remove time from startDate and endDate? Because if startDate's time is later than stopDate's time, it won't include stopDate in the result, right?
@Hp93 Not sure exactly what your talking about. If you run the fiddle I provided you will see that it covers that situation.
|
162

I looked all the ones above. Ended up writing myself. You do not need momentjs for this. A native for loop is enough and makes most sense because a for loop exists to count values in a range.

One Liner:

const getDaysArray = function(s,e) {const a=[];for(const d=new Date(s);d<=new Date(e);d.setDate(d.getDate()+1)){ a.push(new Date(d));}return a;};

Long Version

const getDaysArray = function(start, end) {
    const arr = [];
    for(const dt=new Date(start); dt<=new Date(end); dt.setDate(dt.getDate()+1)){
        arr.push(new Date(dt));
    }
    return arr;
};

List dates in between:

const daylist = getDaysArray(new Date("2018-05-01"),new Date("2018-07-01"));
daylist.map((v)=>v.toISOString().slice(0,10)).join("")
/*
Output: 
    "2018-05-01
    2018-05-02
    2018-05-03
    ...
    2018-06-30
    2018-07-01"
*/

Days from a past date until now:

const daylist = getDaysArray(new Date("2018-05-01"),new Date());
daylist.map((v)=>v.toISOString().slice(0,10)).join("")

6 Comments

What if you want to fetch all the days you specified in getDaysArray? Not the days between it.
working good, but too bad a for(;;) loop is not so readable to the software maintenance when you are working with a lot of other people.
This won't work as expected when there is a time change in the date span (e.g. switch from summer time/DST to standard time). You'll end up with the last day missing. Can be prevented though by specifically setting the time.
Works like a charm! However, I would make one more addition. dt<=end to dt<=new Date(end)
dayList.map(v => v.toISOString().split("T")[0]) this returns a nice array of all the dateStrings in between, pretty handy
|
79

Try this, remember to include moment js,

function getDates(startDate, stopDate) {
    var dateArray = [];
    var currentDate = moment(startDate);
    var stopDate = moment(stopDate);
    while (currentDate <= stopDate) {
        dateArray.push( moment(currentDate).format('YYYY-MM-DD') )
        currentDate = moment(currentDate).add(1, 'days');
    }
    return dateArray;
}

6 Comments

Just a minor improvement: shorthand notation for creating arrays is recommended var dateArray = []; Details here
It is the new way of defining arrays, and I suppose it is shorter/cleaner.
Important fix: var currentDate = moment(startDate); In case you are using this method twice on the same moment.js dates you will be puzzled why it works just the first time. This happens because javascripts passes objects by reference so the function ends up using the startDate twice (which is allready mutated). Patching the above fix ensures that you are wroking with new and unique moment js objects in function scope. Check this fiddle
It's worth noting that using moment.js is not longer recommended. Development on the project has stopped, and while it will still be maintained, the maintainers recommend finding an alternative.
Just adding a note that this won't work properly when time is specified along with the date. For example, getDates('2021-01-01 23:00:00','2021-01-04 22:00:00') returned ["2021-01-01", "2021-01-02", "2021-01-03"], this doesn't include 2021-01-04
|
37

I had trouble using the answers above. The date ranges were missing single days due to timezone shift caused by the local day light saving time (DST). I implemented a version using UTC dates that fixes that problem:

function dateRange(startDate, endDate, steps = 1) {
  const dateArray = [];
  let currentDate = new Date(startDate);

  while (currentDate <= new Date(endDate)) {
    dateArray.push(new Date(currentDate));
    // Use UTC date to prevent problems with time zones and DST
    currentDate.setUTCDate(currentDate.getUTCDate() + steps);
  }

  return dateArray;
}

const dates = dateRange('2020-09-27', '2020-10-28');
console.log(dates);

Note: Whether a certain timezone or DST is applied, depends entirely on your locale. Overriding this is generally not a good idea. Using UTC dates mitigates most of the time related problems.

Bonus: You can set the time interval for which you want to create timestamps with the optional steps parameter. If you want weekly timetamps set steps to 7.

2 Comments

Thank you for this. It's super useful. I eventually converted to ISO Strings before pushing into the array. I can see myself using this a lot in the future.
new Date(currentDate).toString(); might help.
30

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/

3 Comments

I have download all the files related with it but still it shows the error TypeError: moment.twix is not a function
You might have to include the libraries. In nodejs it goes like, var moment = require('moment'); require('twix');
I think you can simplify this using toArray() instead of iterate(): moment.twix(new Date('2012-01-15'),new Date('2012-01-20')).toArray("days"); isaaccambron.com/twix.js/docs.html#toarray
26

If you are using moment then you can use their "official plugin" for ranges moment-range and then this becomes trivial.

moment-range node example:

const Moment = require('moment');
const MomentRange = require('moment-range');
const moment = MomentRange.extendMoment(Moment);

const start = new Date("11/30/2018"), end = new Date("09/30/2019")
const range = moment.range(moment(start), moment(end));

console.log(Array.from(range.by('day')))

moment-range browser example:

window['moment-range'].extendMoment(moment);

const start = new Date("11/30/2018"), end = new Date("09/30/2019")
const range = moment.range(moment(start), moment(end));

console.log(Array.from(range.by('day')))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/4.0.1/moment-range.js"></script>

date fns example:

If you are using date-fns then eachDay is your friend and you get by far the shortest and most concise answer:

console.log(dateFns.eachDay(
  new Date(2018, 11, 30),
  new Date(2019, 30, 09)
))
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>

1 Comment

date fns has a breaking change from // v2.0.0 onward It is now eachDayOfInterval( { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) } )
25
var boxingDay = new Date("12/26/2010");
var nextWeek  = boxingDay*1 + 7*24*3600*1000;

function getDates( d1, d2 ){
  var oneDay = 24*3600*1000;
  for (var d=[],ms=d1*1,last=d2*1;ms<last;ms+=oneDay){
    d.push( new Date(ms) );
  }
  return d;
}

getDates( boxingDay, nextWeek ).join("\n");
// Sun Dec 26 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Mon Dec 27 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Tue Dec 28 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Wed Dec 29 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Thu Dec 30 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Fri Dec 31 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Sat Jan 01 2011 00:00:00 GMT-0700 (Mountain Standard Time)

2 Comments

To be safe, unlike the above, you should usually choose a time in the middle of the day to avoid slight variations due to daylight-savings.
I wish you'd also add middle of the day change to the code as well.
17
function (startDate, endDate, addFn, interval) {

 addFn = addFn || Date.prototype.addDays;
 interval = interval || 1;

 var retVal = [];
 var current = new Date(startDate);

 while (current <= endDate) {
  retVal.push(new Date(current));
  current = addFn.call(current, interval);
 }

 return retVal;

}

1 Comment

This would freeze if you provide dates in incorrect order
14

Using ES6 you have Array.from meaning you can write a really elegant function, that allows for dynamic Intervals (hours, days, months).

function getDates(startDate, endDate, interval) {
const duration = endDate - startDate;
const steps = duration / interval;
return Array.from({length: steps+1}, (v,i) => new Date(startDate.valueOf() + (interval * i)));
}
const startDate = new Date(2017,12,30);
const endDate = new Date(2018,1,3);
const dayInterval = 1000 * 60 * 60 * 24; // 1 day
const halfDayInterval = 1000 * 60 * 60 * 12; // 1/2 day

console.log("Days", getDates(startDate, endDate, dayInterval));
console.log("Half Days", getDates(startDate, endDate, halfDayInterval));

1 Comment

"Elegant" depends on your point of view. new Date(2017,12,30) is 30 Jan 2018, for me the date range starts on 29 Jan 2018. Not all days are 8.64e7 ms (24 hr) long where daylight saving is observed. ;-)
9

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)

Comments

8

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"]

Comments

7

I have been using @Mohammed Safeer solution for a while and I made a few improvements. Using formated dates is a bad practice while working in your controllers. moment().format() should be used only for display purposes in views. Also remember that moment().clone() ensures separation from input parameters, meaning that the input dates are not altered. I strongly encourage you to use moment.js when working with dates.

Usage:

  • Provide moment.js dates as values for startDate, endDate parameters
  • interval parameter is optional and defaults to 'days'. Use intervals suported by .add() method (moment.js). More details here
  • total parameter is useful when specifying intervals in minutes. It defaults to 1.

Invoke:

var startDate = moment(),
    endDate = moment().add(1, 'days');

getDatesRangeArray(startDate, endDate, 'minutes', 30);

Function:

var getDatesRangeArray = function (startDate, endDate, interval, total) {
    var config = {
            interval: interval || 'days',
            total: total || 1
        },
        dateArray = [],
        currentDate = startDate.clone();

    while (currentDate < endDate) {
        dateArray.push(currentDate);
        currentDate = currentDate.clone().add(config.total, config.interval);
    }

    return dateArray;
};

Comments

6
var listDate = [];
var startDate ='2017-02-01';
var endDate = '2017-02-10';
var dateMove = new Date(startDate);
var strDate = startDate;

while (strDate < endDate){
  var strDate = dateMove.toISOString().slice(0,10);
  listDate.push(strDate);
  dateMove.setDate(dateMove.getDate()+1);
};
console.log(listDate);

//["2017-02-01", "2017-02-02", "2017-02-03", "2017-02-04", "2017-02-05", "2017-02-06", "2017-02-07", "2017-02-08", "2017-02-09", "2017-02-10"]

4 Comments

Please add more description and/or information about your answer and how it solves the asked problem so others can easily understand it without asking for clarification
I find this is skipping 2016-03-31 for some reason!
You should not have var before strDate inside the while loop!
Works like charm for me :)
6

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);
}

Comments

6
Array(7).fill().map((_,i) => dayjs().subtract(i, "day").format("YYYY-MM-DD"));

2 Comments

Awesome mate! FYI, you have to use/install DayJs dependency. I added a .reverse() at the end to get the dates in an ascendent order!
Thanks, May and ThisIsMyName. I was wondering how others were doing this. The only real edit I made was for ES6: [...Array(7)].map((_, i) => startOfWeek.add(i, 'day')), where startOfWeek is a dayjs object, e.g. dates.get(date).startOf('week').subtract(-1, 'week')
5

That's another few lines solution using date-fns library:

const { format, differenceInDays, addDays } = dateFns;

const getRangeDates = (startDate, endDate) => {
  const days = differenceInDays(endDate, startDate);
  console.log([...Array(days + 1).keys()].map((i) => format(addDays(startDate, i), 'YYYY-MM-DD')));
};

getRangeDates('2021-06-01', '2021-06-05');
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js"></script>

Comments

4

Not a shortest possible but easy, immutable and without dependencies

function datesArray(start, end) {
    let result = [], current = new Date(start);
    while (current <= end)
        result.push(current) && (current = new Date(current)) && current.setDate(current.getDate() + 1);
    return result;
}

Usage

function datesArray(start, end) {
    let result = [], current = new Date(start);
    while (current <= end)
        result.push(current) && (current = new Date(current)) && current.setDate(current.getDate() + 1);
    return result;
 }

//  Usage

const test = datesArray(
  new Date('2020-02-26'), 
  new Date('2020-03-05')
 );

for (let i = 0; i < test.length; i ++ ) {
    console.log(
      test[i].toISOString().slice(0,10)
    );
}

Comments

4

Using JavaScript

const getDatesBetween = (startDate, endDate, includeEndDate) => {
    const dates = [];
    const currentDate = startDate;
    while (currentDate < endDate) {
        dates.push(new Date(currentDate));
        currentDate.setDate(currentDate.getDate() + 1);
    }
    if (includeEndDate) dates.push(endDate);
    return dates;
};

Using TypeScript

const getDatesBetween = (
  startDate: Date,
  endDate: Date,
  includeEndDate?: boolean
) => {
  const dates = [];
  const currentDate = startDate;
  while (currentDate < endDate) {
    dates.push(new Date(currentDate));
    currentDate.setDate(currentDate.getDate() + 1);
  }
  if (includeEndDate) dates.push(endDate);
  return dates;
};

Example

console.log(getDatesBetween(new Date(2020, 0, 1), new Date(2020, 0, 3)));
console.log(getDatesBetween(new Date(2020, 0, 1), new Date(2020, 0, 3), true));

Comments

3

Here's a one liner that doesn't require any libraries in-case you don't want to create another function. Just replace startDate (in two places) and endDate (which are js date objects) with your variables or date values. Of course you could wrap it in a function if you prefer

Array(Math.floor((endDate - startDate) / 86400000) + 1).fill().map((_, idx) => (new Date(startDate.getTime() + idx * 86400000)))

1 Comment

this doesn't take into consideration Daylight/Standard Savings Time changes.. some days are longer and some are shorter
3

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;
}

Comments

3

You can do it easily using momentJS

Add moment to your dependencies

npm i moment

Then import that in your file

var moment = require("moment");

Then use the following code to get the list of all dates between two dates

let dates = [];
let currDate = moment.utc(new Date("06/30/2019")).startOf("day");
let lastDate = moment.utc(new Date("07/30/2019")).startOf("day");

do {
 dates.push(currDate.clone().toDate());
} while (currDate.add(1, "days").diff(lastDate) < 0);
dates.push(currDate.clone().toDate());

console.log(dates);

Comments

2

d3js provides a lot of handy functions and includes d3.time for easy date manipulations

https://github.com/d3/d3-time

For your specific request:

Utc

var range = d3.utcDay.range(new Date(), d3.utcDay.offset(new Date(), 7));

or local time

var range = d3.timeDay.range(new Date(), d3.timeDay.offset(new Date(), 7));

range will be an array of date objects that fall on the first possible value for each day

you can change timeDay to timeHour, timeMonth etc for the same results on different intervals

Comments

2

@softvar's solution, but then including working dates option

/**
 * Returns array of working days between two dates.
 *
 * @param {string} startDate
 *   The start date in yyyy-mm-dd format.
 * @param {string} endDate
 *   The end date in yyyy-mm-dd format.
 * @param {boolean} onlyWorkingDays
 *   If true only working days are returned. Default: false
 *
 * @return {array}
 *   Array of dates in yyyy-mm-dd string format.
 */
function getDates(startDate, stopDate, onlyWorkingDays) {
  let doWd = typeof onlyWorkingDays ==='undefined' ? false : onlyWorkingDays;

  let dateArray = [];  
  let dayNr;
  let runDateObj = moment(startDate);  
  let stopDateObj = moment(stopDate);

  while (runDateObj <= stopDateObj) {
    dayNr = runDateObj.day();
    if (!doWd || (dayNr>0 && dayNr<6)) {
     dateArray.push(moment(runDateObj).format('YYYY-MM-DD'));  
    }

    runDateObj = moment(runDateObj).add(1, 'days');
  }
  return dateArray;
}

Comments

2

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))
}

Comments

1

Note: I'm aware this is slightly different than the requested solution, but I think many will find it useful.

If you want to find each "x" intervals (days, months, years, etc...) between two dates, moment.js and the moment-range extension packages enable this functionality.

For example, to find each 30th day between two dates:

window['moment-range'].extendMoment(moment);

var dateString = "2018-05-12 17:32:34.874-08";
var start  = new Date(dateString);
var end    = new Date();
var range1 = moment.range(start, end);
var arrayOfIntervalDates = Array.from(range1.by('day', { step: 30 }));

arrayOfIntervalDates.map(function(intervalDate){
  console.log(intervalDate.format('YY-M-DD'))
});

Comments

1
  1. Generate an array of years:

    const DAYS = () => {
     const days = []
     const dateStart = moment()
     const dateEnd = moment().add(30, ‘days')
     while (dateEnd.diff(dateStart, ‘days') >= 0) {
      days.push(dateStart.format(‘D'))
      dateStart.add(1, ‘days')
     }
     return days
    }
    console.log(DAYS())
    
  2. Generate an arrays for month:

            const MONTHS = () => {
             const months = []
             const dateStart = moment()
             const dateEnd = moment().add(12, ‘month')
             while (dateEnd.diff(dateStart, ‘months') >= 0) {
              months.push(dateStart.format(‘M'))
              dateStart.add(1, ‘month')
             }
             return months
            }
            console.log(MONTHS())
    
  3. Generate an arrays for days:

            const DAYS = () => {
             const days = []
             const dateStart = moment()
             const dateEnd = moment().add(30, ‘days')
             while (dateEnd.diff(dateStart, ‘days') >= 0) {
              days.push(dateStart.format(‘D'))
              dateStart.add(1, ‘days')
             }
             return days
            }
            console.log(DAYS())
    

Comments

1

Using lodash & moment:

const startDate = moment();
_.range(0, 7).map((d) => startDate.clone().add(d, 'day').toDate())

Comments

1

This variant solves an issue in most of the answers given here: when the time of the end date is prior than the time of the start date, the last date will not be included in the resulting array.

function getDatesInRange(startDate, endDate) {
    const start = new Date(startDate);
    const dates = [];

    while (start.toISOString().slice(0, 10) <= endDate.toISOString().slice(0, 10)) {
        dates.push(new Date(start));
        start.setDate(start.getDate() + 1);
    }

    return dates;
}

By comparing the partial ISO string representation of the two dates we make sure only days are being counted.

Comments

0

This may help someone,

You can get the row output from this and format the row_date object as you want.

var from_date = '2016-01-01';
var to_date = '2016-02-20';

var dates = getDates(from_date, to_date);

console.log(dates);

function getDates(from_date, to_date) {
  var current_date = new Date(from_date);
  var end_date     = new Date(to_date);

  var getTimeDiff = Math.abs(current_date.getTime() - end_date.getTime());
  var date_range = Math.ceil(getTimeDiff / (1000 * 3600 * 24)) + 1 ;

  var weekday = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
  var months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
  var dates = new Array();

  for (var i = 0; i <= date_range; i++) {
     var getDate, getMonth = '';

     if(current_date.getDate() < 10) { getDate = ('0'+ current_date.getDate());}
     else{getDate = current_date.getDate();}

    if(current_date.getMonth() < 9) { getMonth = ('0'+ (current_date.getMonth()+1));}
    else{getMonth = current_date.getMonth();}

    var row_date = {day: getDate, month: getMonth, year: current_date.getFullYear()};
    var fmt_date = {weekDay: weekday[current_date.getDay()], date: getDate, month: months[current_date.getMonth()]};
    var is_weekend = false;
    if (current_date.getDay() == 0 || current_date.getDay() == 6) {
        is_weekend = true;
    }
    dates.push({row_date: row_date, fmt_date: fmt_date, is_weekend: is_weekend});
    current_date.setDate(current_date.getDate() + 1);
 }
 return dates;
}

https://gist.github.com/pranid/3c78f36253cbbc6a41a859c5d718f362.js

Comments

0

Here's a canned method that will accept Moment dates or strings or a mixture as inputs and generate an array of dates as Moment dates. If you don't want Moment dates as output then change what the map() method returns.

const moment = require('moment');

// ...

/**
 * @param {string|import('moment').Moment} start
 * @param {string|import('moment').Moment} end
 * @returns {import('moment').Moment[]}
 */
const getDateRange = (start, end) => {
  const s = moment.isMoment(start) ? start : moment(start);
  const e = moment.isMoment(end) ? end : moment(end);
  return [...Array(1 + e.diff(s, 'days')).keys()].map(n => moment(s).add(n, 'days'));
};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.