Javascript - get array of dates between 2 dates
Asked Answered
L

34

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

Livvyy answered 10/12, 2010 at 21:46 Comment(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.Beta
L
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;

}
Livvyy answered 10/12, 2010 at 22:47 Comment(1)
This would freeze if you provide dates in incorrect orderMutt
W
248
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/

Wineshop answered 10/12, 2010 at 22:7 Comment(12)
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.Livvyy
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.Amerson
@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.Wineshop
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?Goldshell
@Goldshell Not sure exactly what your talking about. If you run the fiddle I provided you will see that it covers that situation.Wineshop
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: fiddleGoldshell
@Goldshell 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.Wineshop
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?Lyudmila
Worked fine for me 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.Wineshop
nice but it will change startDate and stopDate alwoParamedical
clone and send date Date.prototype.clone = function (): Date { return new Date(+this); }; otherwise start and stop date will also changedParamedical
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))Inartificial
V
155

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("")
Valois answered 17/5, 2018 at 18:21 Comment(10)
What if you want to fetch all the days you specified in getDaysArray? Not the days between it.Cinereous
thanks! exactly what I needed with no dependencies. :)Allaround
this function manipulates the source input date. :) I tested it.Carpeting
@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), ...). ;-)Libratory
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.Piliferous
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.Dachi
Works like a charm! However, I would make one more addition. dt<=end to dt<=new Date(end)Smacking
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 firstMenial
dayList.map(v => v.toISOString().split("T")[0]) this returns a nice array of all the dateStrings in between, pretty handyEvan
You're setting arr out of scope. You should do something like this: ` const getDaysArray = (startDate, endDate) => { let daysArray = [] for (let dt = new Date(startDate); dt <= new Date(endDate); dt.setDate(dt.getDate() + 1)) { daysArray.push(new Date(dt).toISOString().slice(0, 10)); } return daysArray; }; `Coping
T
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;
}
Tifanie answered 6/7, 2015 at 17:13 Comment(6)
Just a minor improvement: shorthand notation for creating arrays is recommended var dateArray = []; Details hereSecularity
It is the new way of defining arrays, and I suppose it is shorter/cleaner.Tifanie
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 fiddleSecularity
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.Peseta
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-04Rowlett
thanks, using moment gap between to dates can be large: (getDates(new Date('2018-01-01'), new Date('2028-07-01'))Marpet
H
31

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.

Hardigg answered 29/10, 2020 at 13:48 Comment(2)
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.Ptolemaic
new Date(currentDate).toString(); might help.Beyond
F
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/

Flivver answered 8/4, 2013 at 14:48 Comment(3)
I have download all the files related with it but still it shows the error TypeError: moment.twix is not a functionAmerson
You might have to include the libraries. In nodejs it goes like, var moment = require('moment'); require('twix');Alpinist
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#toarrayFilicide
A
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)
Arva answered 10/12, 2010 at 22:2 Comment(2)
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.Arva
I wish you'd also add middle of the day change to the code as well.Westphal
E
24

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>
Estaminet answered 5/12, 2018 at 21:22 Comment(1)
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) } )Guanine
L
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;

}
Livvyy answered 10/12, 2010 at 22:47 Comment(1)
This would freeze if you provide dates in incorrect orderMutt
P
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));
Peppers answered 1/3, 2018 at 21:18 Comment(1)
"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. ;-)Libratory
D
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)
Davon answered 21/1, 2018 at 12:36 Comment(0)
D
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"]
Dolph answered 19/3, 2015 at 12:54 Comment(0)
S
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;
};
Secularity answered 3/9, 2015 at 11:12 Comment(0)
N
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"]
Nob answered 2/3, 2017 at 3:34 Comment(4)
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 clarificationEmaciation
I find this is skipping 2016-03-31 for some reason!Boudicca
You should not have var before strDate inside the while loop!Rambunctious
Works like charm for me :)Alveolus
F
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);
}
Foulup answered 7/12, 2017 at 13:0 Comment(0)
H
6
Array(7).fill().map((_,i) => dayjs().subtract(i, "day").format("YYYY-MM-DD"));
Hedonics answered 16/3, 2021 at 9:20 Comment(2)
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!Humility
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')Brazzaville
R
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>
Rhodes answered 4/6, 2021 at 11:24 Comment(0)
S
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));
Sweetbrier answered 22/11, 2021 at 10:35 Comment(0)
P
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)))
Portable answered 13/7, 2017 at 0:3 Comment(1)
this doesn't take into consideration Daylight/Standard Savings Time changes.. some days are longer and some are shorterCairistiona
D
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;
}
Dugong answered 11/12, 2019 at 10:5 Comment(0)
C
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);
Cheke answered 22/7, 2020 at 3:28 Comment(0)
A
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)
    );
}
Associative answered 11/11, 2021 at 9:15 Comment(0)
D
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

Daukas answered 16/5, 2017 at 22:8 Comment(0)
M
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;
}
Micron answered 7/6, 2019 at 7:11 Comment(0)
B
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))
}
Barbour answered 15/9, 2020 at 13:47 Comment(0)
A
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'))
});
Analects answered 8/1, 2019 at 16:48 Comment(0)
H
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())
    
Hodess answered 23/5, 2020 at 8:24 Comment(0)
E
1

Using lodash & moment:

const startDate = moment();
_.range(0, 7).map((d) => startDate.clone().add(d, 'day').toDate())
Exchequer answered 9/2, 2021 at 23:58 Comment(0)
I
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

Intramuscular answered 25/10, 2016 at 12:36 Comment(0)
S
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'));
};
Southwestwardly answered 24/10, 2018 at 5:13 Comment(0)
S
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

Schnapps answered 2/7, 2019 at 1:48 Comment(0)
M
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;
}
Moreville answered 16/6, 2021 at 11:15 Comment(0)
V
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))
Vaporimeter answered 31/3, 2023 at 7:24 Comment(0)
L
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.

Liesa answered 11/5, 2023 at 5:13 Comment(0)
J
0

I used dayjs package to do this

Simple explanation: dayjs has a function isBefore where you can check if the start date is before the end date. if that becomes true then push that date to an array and add 1 day. then do this on a while loop and you will get the list of dates.

import dayjs from "dayjs";
import { months } from "../constants/months"; // ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec]

/* The `interface Dates` is defining the structure of an object that will be returned by the
`getListOfDays` function. It specifies the properties and their types that the object should have. */
interface Dates {
    length: number;
    readable: string[];
    dates: dayjs.Dayjs[];
    months: string[];
    years: number[];
}

export default function getListOfDays(start: dayjs.Dayjs, end: dayjs.Dayjs): Dates {

    /* The code is declaring and initializing a variable named `obj` with an object of type `Dates`. The
    `Dates` interface defines the structure of the object. */
    let obj: Dates = {
        length: 0,
        readable: [],
        dates: [],
        months: [],
        years: [],
    }

    /* `let current = start;` is assigning the value of the `start` variable to the `current` variable.
    This is done to ensure that the original `start` variable is not modified during the execution
    of the code. */
    let current = start;


    /* The code block is a while loop that iterates as long as the `current` date is before the `end` date. */
    while (current.isBefore(end.add(1, "day"))) {
        obj.dates.push(current);
        obj.readable.push(current.format("MMMM DD, YYYY"));
        obj.length += 1;
        obj.months.push(months[current.month()]);
        obj.years.push(current.year());
        current = current.add(1, "day");
    }

    /* The code `obj.months = [...new Set(obj.months)];` and `obj.years = [...new Set(obj.years)];` are
    removing duplicate values from the `obj.months` and `obj.years` arrays, respectively. */
    obj.months = [...new Set(obj.months)];
    obj.years = [...new Set(obj.years)];

    return obj;
}
Joselynjoseph answered 22/11, 2023 at 12:36 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.