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

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Scott Klarenbach
  • 37,171
  • 15
  • 62
  • 91
  • If date-fns is allowed to use, `eachDayOfInterval` [1](https://date-fns.org/v2.29.3/docs/eachDayOfInterval) and `addDays` [2](https://date-fns.org/v2.29.3/docs/addDays) are what can be used to return an array of dates between start date and end date. – tinystone Dec 10 '22 at 12:52

33 Answers33

245
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/

Legionar
  • 7,472
  • 2
  • 41
  • 70
John Hartsock
  • 85,422
  • 23
  • 131
  • 146
  • 2
    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. – Scott Klarenbach Dec 10 '10 at 22:46
  • 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. – vaibhav kulkarni Jul 22 '15 at 07:27
  • @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. – John Hartsock Aug 11 '15 at 00:40
  • 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 Jun 11 '16 at 18:00
  • @Hp93 Not sure exactly what your talking about. If you run the fiddle I provided you will see that it covers that situation. – John Hartsock Jun 15 '16 at 17:03
  • I mean, if d2 = d1 +2 days and setHour(1,0,0,0). If so getDates(d1,d2) will only return 2 days and not include the third day. Of course it might be intent to work like this, but in my case, I want to get all days involved in. Here a fiddle based on your: [fiddle](http://jsfiddle.net/ow7ywsL7/) – Hp93 Jun 17 '16 at 03:11
  • @Hp93 Your issue is fairly easy to account for if you simply remove the time element. I had the parameters for input described by OP and I followed them to assist a specific question. As for what your asking, simply remove the time element from the date. – John Hartsock Jun 20 '16 at 16:22
  • Does not work correctly for me. Skips few days. Like 1.1.2017, 1.2, 1.4, 1.5, 1.7. (m.d.y). any idea? – Erik Kubica Jul 23 '17 at 19:31
  • Worked fine for me http://jsfiddle.net/cM3ZU/1326/ have a look at the modified example. I believe you may be running into a formating issue with the dates. I am using m/d/yyyy as my format. – John Hartsock Aug 07 '17 at 20:21
  • nice but it will change startDate and stopDate alwo – Janak Bhatta Sep 07 '17 at 17:22
  • clone and send date Date.prototype.clone = function (): Date { return new Date(+this); }; otherwise start and stop date will also changed – Janak Bhatta Sep 07 '17 at 17:30
  • This function does not work when changing the clocks (summer to winter). For example, in Europe, with October 26 included, it will not return the correct array. This can be corrected by changing the while line to this : `while (currentDate.setHours(0,0,0) <= stopDate.setHours(0,0,0))` – Fire Druid Oct 05 '20 at 07:43
149

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:

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

Long Version

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

List dates in between:

var 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:

var daylist = getDaysArray(new Date("2018-05-01"),new Date());
daylist.map((v)=>v.toISOString().slice(0,10)).join("")
Rikky
  • 103
  • 4
enesn
  • 2,063
  • 1
  • 10
  • 13
  • What if you want to fetch all the days you specified in `getDaysArray`? Not the days between it. – Blues Clues Aug 24 '18 at 03:33
  • thanks! exactly what I needed with no dependencies. :) – mpsyp Sep 12 '18 at 19:49
  • 5
    this function manipulates the source input date. :) I tested it. – Hamed Taheri Oct 18 '19 at 10:34
  • 5
    @HamedTaheri—yes, but that can be fixed by assigning a copy of *start* to *dt* rather than *start* itself, e.g. `for (var arr=[], dt=new Date(start), ...)`. ;-) – RobG Nov 06 '19 at 00:38
  • 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. – Victor Dec 10 '19 at 22:33
  • 4
    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. – Felix Wienberg Nov 16 '20 at 08:33
  • 1
    Works like a charm! However, I would make one more addition. ```dt<=end``` to ```dt<=new Date(end)``` – Srinath Kamath Dec 01 '20 at 12:00
  • 1
    **does it return `[]` for you?** ... you have to input date object e.g. like `new Date("2021-03-01")` **not** just `"2021-03-01"` for example :-) I missed this at first – jave.web Nov 01 '21 at 14:02
  • dayList.map(v => v.toISOString().split("T")[0]) this returns a nice array of all the dateStrings in between, pretty handy – DanteDX May 18 '22 at 18:42
78

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;
}
softvar
  • 17,917
  • 12
  • 55
  • 76
Mohammed Safeer
  • 20,751
  • 8
  • 75
  • 78
  • Just a minor improvement: shorthand notation for creating arrays is recommended `var dateArray = [];` Details [here](http://stackoverflow.com/questions/931872/what-s-the-difference-between-array-and-while-declaring-a-javascript-ar) – Adrian Moisa Aug 19 '15 at 14:43
  • It is the new way of defining arrays, and I suppose it is shorter/cleaner. – Mohammed Safeer Aug 20 '15 at 09:21
  • 2
    **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](http://jsfiddle.net/adrian_moisa/x076j4dh/8/) – Adrian Moisa Aug 20 '15 at 13:29
  • 8
    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. – Albert MN. Sep 21 '20 at 18:30
  • 1
    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` – Arun A S Jan 30 '21 at 07:40
  • thanks, using moment gap between to dates can be large: (getDates(new Date('2018-01-01'), new Date('2028-07-01')) – Rafiq Apr 20 '23 at 09:43
30

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.

stekhn
  • 1,969
  • 2
  • 25
  • 38
29

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/

l2aelba
  • 21,591
  • 22
  • 102
  • 138
Ahmed Aswani
  • 8,271
  • 7
  • 33
  • 54
  • I have download all the files related with it but still it shows the error TypeError: moment.twix is not a function – vaibhav kulkarni Jul 22 '15 at 07:24
  • You might have to include the libraries. In nodejs it goes like, var moment = require('moment'); require('twix'); – Dr Bala Soundararaj Jan 02 '17 at 20:50
  • 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");` http://isaaccambron.com/twix.js/docs.html#toarray – Kimeiga Feb 21 '21 at 23:11
24
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)
Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • 3
    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. – Phrogz Dec 10 '10 at 22:14
  • I wish you'd also add middle of the day change to the code as well. – chickens May 17 '18 at 17:40
22

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>
Akrion
  • 18,117
  • 1
  • 34
  • 54
  • 7
    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) } ) – Mads Hjorth Aug 10 '21 at 18:32
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;

}
Scott Klarenbach
  • 37,171
  • 15
  • 62
  • 91
13

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));
digiguru
  • 12,724
  • 20
  • 61
  • 87
  • 6
    "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. ;-) – RobG Nov 06 '19 at 00:43
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)
Ray Jennings
  • 336
  • 2
  • 10
Irfy
  • 2,469
  • 4
  • 25
  • 31
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"]
gor181
  • 1,988
  • 1
  • 14
  • 12
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;
};
Adrian Moisa
  • 3,923
  • 7
  • 41
  • 66
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"]
Công Thắng
  • 275
  • 3
  • 5
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);
}
Afeesudheen
  • 936
  • 2
  • 12
  • 21
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
5
Array(7).fill().map((_,i) => dayjs().subtract(i, "day").format("YYYY-MM-DD"));
May Noppadol
  • 638
  • 8
  • 9
  • 1
    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! – ThisIsMyName Jul 21 '21 at 12:03
  • 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')` – luzmcosta Aug 26 '21 at 16:43
4

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>
Flavio Del Grosso
  • 490
  • 2
  • 7
  • 21
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));
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)))
ti994a
  • 47
  • 2
  • this doesn't take into consideration Daylight/Standard Savings Time changes.. some days are longer and some are shorter – Mike May 06 '19 at 03:06
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;
}
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);
Nitesh Malviya
  • 794
  • 1
  • 9
  • 17
3

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

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;
}
koosvdkolk
  • 341
  • 2
  • 4
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))
}
sai_ekkaldevi
  • 103
  • 1
  • 6
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'))
});
Stone
  • 2,608
  • 26
  • 26
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())
    
elnaz nasiri
  • 155
  • 1
  • 4
1

Using lodash & moment:

const startDate = moment();
_.range(0, 7).map((d) => startDate.clone().add(d, 'day').toDate())
nite
  • 970
  • 9
  • 17
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

Praneeth Nidarshan
  • 1,704
  • 15
  • 21
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'));
};
Guy
  • 65,082
  • 97
  • 254
  • 325
0

Function:

  var dates = [],
      currentDate = startDate,
      addDays = function(days) {
        var 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:

var dates = getDatesRange(new Date(2019,01,01), new Date(2019,01,25));                                                                                                           
dates.forEach(function(date) {
  console.log(date);
});

Hope it helps you

Hieu Dang
  • 343
  • 3
  • 11
0
getDates = (from, to) => {
    const cFrom = new Date(from);
    const cTo = new Date(to);

    let daysArr = [new Date(cFrom)];
    let tempDate = cFrom;

    while (tempDate < cTo) {
        tempDate.setUTCDate(tempDate.getUTCDate() + 1);
        daysArr.push(new Date(tempDate));
    }

    return daysArr;
}
Ehsan Hejazi
  • 176
  • 1
  • 11
0

you can use the third parameter as an interval

function arrayDateRange(start, stop, step) {
    if (step < 1000) return [start, stop];
    return Array.from({ length: (stop - start) / step + 1 }, (value, index) => {
        return new Date(start.getTime() + index * step)
    });
}

arrayDateRange(new Date('2023-01-01'),new Date('2023-01-15'),(1000*60*60*24))
Deyan
  • 11
  • 3
0

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.

Alex_89
  • 371
  • 5
  • 15