Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get dates in between two dates with JavaScript.
// Returns an array of dates between the two dates
var getDates = function(startDate, endDate) {
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 = getDates(new Date(2013,10,22), new Date(2013,11,25));
dates.forEach(function(date) {
console.log(date);
});
@andreibecker

This comment has been minimized.

Copy link

@andreibecker andreibecker commented Jul 13, 2016

Very good, solve my problem.

@JockPerkins

This comment has been minimized.

Copy link

@JockPerkins JockPerkins commented Jan 19, 2017

Worked perfectly, thanks!

@sibelius

This comment has been minimized.

Copy link

@sibelius sibelius commented Mar 7, 2017

I made something more generic

it uses date-fns and does not mutate the array

import { addDays, addMonths, differenceInDays, differenceInMonths  } from 'date-fns';

import { PERIOD } from './PeriodEnumType';

export function dateRange(startDate, endDate, interval) {
  if (interval === PERIOD.DAY) {
    const days = differenceInDays(endDate, startDate);

    return [...Array(days+1).keys()].map((i) => addDays(startDate, i));
  }

  if (interval === PERIOD.MONTH) {
    const months = differenceInMonths(endDate, startDate);

    return [...Array(months+1).keys()].map((i) => addMonths(startDate, i));
  }
}
@barmao

This comment has been minimized.

Copy link

@barmao barmao commented Sep 5, 2017

Works pretty well.. Thank you alot!!

@Ben52

This comment has been minimized.

Copy link

@Ben52 Ben52 commented Sep 7, 2017

Here's a function to get a range of dates, split up by any key, ex. month, day, year, etc.

const moment = require('moment');

function getRangeOfDates(start, end, key, arr = [start.startOf(key)]) {
  
  if(start.isAfter(end)) throw new Error('start must precede end')
  
  const next = moment(start).add(1, key).startOf(key);
  
  
  if(next.isAfter(end, key)) return arr;
  

  return getRangeOfDates(next, end, key, arr.concat(next));
  
}

So if I wanted to get an array of months from the start of the year until a year from now, I would go:

const begin = moment().startOf('year')
const end = moment().add(1, 'year')

getRangeOfDates(begin, end, 'month');

Which would return:

[ moment("2017-01-01T00:00:00.000"),
  moment("2017-02-01T00:00:00.000"),
  moment("2017-03-01T00:00:00.000"),
  moment("2017-04-01T00:00:00.000"),
  moment("2017-05-01T00:00:00.000"),
  moment("2017-06-01T00:00:00.000"),
  moment("2017-07-01T00:00:00.000"),
  moment("2017-08-01T00:00:00.000"),
  moment("2017-09-01T00:00:00.000"),
  moment("2017-10-01T00:00:00.000"),
  moment("2017-11-01T00:00:00.000"),
  moment("2017-12-01T00:00:00.000"),
  moment("2018-01-01T00:00:00.000"),
  moment("2018-02-01T00:00:00.000"),
  moment("2018-03-01T00:00:00.000"),
  moment("2018-04-01T00:00:00.000"),
  moment("2018-05-01T00:00:00.000"),
  moment("2018-06-01T00:00:00.000"),
  moment("2018-07-01T00:00:00.000"),
  moment("2018-08-01T00:00:00.000"),
  moment("2018-09-01T00:00:00.000") ]

@baladkb

This comment has been minimized.

Copy link

@baladkb baladkb commented Jan 5, 2018

@miguelmota thanks :octocat:

@googlicius

This comment has been minimized.

Copy link

@googlicius googlicius commented Jan 10, 2018

Many thanks 😍

@jacintoface

This comment has been minimized.

Copy link

@jacintoface jacintoface commented Jan 18, 2018

Thank You very much

@hriziya

This comment has been minimized.

Copy link

@hriziya hriziya commented Apr 25, 2018

Thanks @Ben52

@cyberundertakor

This comment has been minimized.

Copy link

@cyberundertakor cyberundertakor commented May 14, 2018

Thanks @Ben52

@aalexgabi

This comment has been minimized.

Copy link

@aalexgabi aalexgabi commented May 18, 2018

My version which strips hours, minutes, seconds etc. and does not declare an inline function:

// Returns an array of dates between the two dates
const getDatesBetween = (startDate, endDate) => {
    const dates = [];

    // Strip hours minutes seconds etc.
    let currentDate = new Date(
        startDate.getFullYear(),
        startDate.getMonth(),
        startDate.getDate()
    );

    while (currentDate <= endDate) {
        dates.push(currentDate);

        currentDate = new Date(
            currentDate.getFullYear(),
            currentDate.getMonth(),
            currentDate.getDate() + 1, // Will increase month if over range
        );
    }

    return dates;
};

// Usage
const dates = getDates(new Date(2018, 0, 30, 11, 30), new Date(2018, 2, 2, 23, 59, 59)); 

console.log(dates);
@hieudang59

This comment has been minimized.

Copy link

@hieudang59 hieudang59 commented Jun 4, 2018

Thanks @aalexgabi, it resolved my problem 💯

@dibyasipu

This comment has been minimized.

Copy link

@dibyasipu dibyasipu commented Jul 17, 2018

Help me sir,
how to check between two date range???
Example

from date=03-07-2018
to date=13-07-2018

how to check date range between them in javascript

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Jul 25, 2018

@sibelius can you elaborate on how you use that function? For instance, it looks like you have another file you are including. What does that look like? Thanks in advance!

@wadadaaa

This comment has been minimized.

Copy link

@wadadaaa wadadaaa commented Oct 24, 2018

import moment from 'moment';
getStandAge = startDate => { const age = moment().diff(startDate, 'months'); return isNaN(age) ? null : age; };

@pumpin101

This comment has been minimized.

Copy link

@pumpin101 pumpin101 commented Oct 29, 2018

Please i would need help, i would like to do this using two date time picker and insert the dates in between the date time picker in a database but i dont know how to go about this in vb.net. Someone should help me please

@pumpin101

This comment has been minimized.

Copy link

@pumpin101 pumpin101 commented Oct 29, 2018

I made something more generic

it uses date-fns and does not mutate the array

import { addDays, addMonths, differenceInDays, differenceInMonths  } from 'date-fns';

import { PERIOD } from './PeriodEnumType';

export function dateRange(startDate, endDate, interval) {
  if (interval === PERIOD.DAY) {
    const days = differenceInDays(endDate, startDate);

    return [...Array(days+1).keys()].map((i) => addDays(startDate, i));
  }

  if (interval === PERIOD.MONTH) {
    const months = differenceInMonths(endDate, startDate);

    return [...Array(months+1).keys()].map((i) => addMonths(startDate, i));
  }
}

Can u help using two date time picker and insert the dates in a database in vb.net

@zeekhan90

This comment has been minimized.

Copy link

@zeekhan90 zeekhan90 commented Nov 8, 2018

Worked Perfectly.... thanks :-)

@nlt2390

This comment has been minimized.

Copy link

@nlt2390 nlt2390 commented Nov 13, 2018

Here's a function to get a range of dates, split up by any key, ex. month, day, year, etc.

const moment = require('moment');

function getRangeOfDates(start, end, key, arr = [start.startOf(key)]) {
  
  if(start.isAfter(end)) throw new Error('start must precede end')
  
  const next = moment(start).add(1, key).startOf(key);
  
  
  if(next.isAfter(end, key)) return arr;
  

  return getRangeOfDates(next, end, key, arr.concat(next));
  
}

So if I wanted to get an array of months from the start of the year until a year from now, I would go:

const begin = moment().startOf('year')
const end = moment().add(1, 'year')

getRangeOfDates(begin, end, 'month');

Which would return:

[ moment("2017-01-01T00:00:00.000"),
  moment("2017-02-01T00:00:00.000"),
  moment("2017-03-01T00:00:00.000"),
  moment("2017-04-01T00:00:00.000"),
  moment("2017-05-01T00:00:00.000"),
  moment("2017-06-01T00:00:00.000"),
  moment("2017-07-01T00:00:00.000"),
  moment("2017-08-01T00:00:00.000"),
  moment("2017-09-01T00:00:00.000"),
  moment("2017-10-01T00:00:00.000"),
  moment("2017-11-01T00:00:00.000"),
  moment("2017-12-01T00:00:00.000"),
  moment("2018-01-01T00:00:00.000"),
  moment("2018-02-01T00:00:00.000"),
  moment("2018-03-01T00:00:00.000"),
  moment("2018-04-01T00:00:00.000"),
  moment("2018-05-01T00:00:00.000"),
  moment("2018-06-01T00:00:00.000"),
  moment("2018-07-01T00:00:00.000"),
  moment("2018-08-01T00:00:00.000"),
  moment("2018-09-01T00:00:00.000") ]

Thanks a lot

@nivduran

This comment has been minimized.

Copy link

@nivduran nivduran commented Apr 16, 2019

It works but I have a problem with the month.
I run it like that:

var dates = getDates(new Date(2019,04,16), new Date(2019,04,17));                                                                                                           
dates.forEach(function(date) {
  console.log(date);
});

And the result is:

Thu May 16 2019 00:00:00 GMT+0300 (Israel Daylight Time)
Fri May 17 2019 00:00:00 GMT+0300 (Israel Daylight Time)

I received May instead of April, why? What am I missing?

@sgerin

This comment has been minimized.

Copy link

@sgerin sgerin commented Apr 17, 2019

Hi @nivduran. When using the Date constructor like that:
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
keep in mind that the monthIndex parameter is 0-based. This means that January = 0 and December = 11.
In your case, you used 4 as the monthIndex parameter, which means the fifth month of the year which is May.

@shippudenmadara

This comment has been minimized.

Copy link

@shippudenmadara shippudenmadara commented May 20, 2019

Thanks @aalexgabi

@kimchicoco

This comment has been minimized.

Copy link

@kimchicoco kimchicoco commented Jul 5, 2019

How about filling missing dates inside arrays

var array=[
{date:"2016-11-17T00:00:00"}, //start
{date:"2016-11-19T00:00:00"},
{date:"2016-11-18T00:00:00"},
{date:"2016-11-21T00:00:00"},
{date:"2016-11-22T00:00:00"},
{date:"2016-11-23T00:00:00"},
{date:"2017-11-27T00:00:00"},//end
];

Actually very useful for charts that has missing data.

@tonioz

This comment has been minimized.

Copy link

@tonioz tonioz commented Aug 22, 2019

Very good, thank you sir!

@MVMurrell

This comment has been minimized.

Copy link

@MVMurrell MVMurrell commented Sep 6, 2019

if you are looking for specific days of the week this will give them to you granted you provide a string array, otherwise, just dont use the if statement .

import * as moment from "moment";
import * as _ from 'lodash';

getDatesOfDays(startDate: moment.Moment, endDate: moment.Moment, dayArray: string[]) {
           var range = [];
           var dayNames = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
        while (moment(startDate) <= moment(endDate)){
            if (dayArray.includes(dayNames[startDate.day()])) {
                range.push(startDate.clone());
            }
            startDate.add(1 , 'days');
        }
        return range;
}
@space-tech0610

This comment has been minimized.

Copy link

@space-tech0610 space-tech0610 commented Oct 15, 2019

https://gist.github.com/miguelmota/7905510#file-getdates-js
It's very pretty.
I solved my problem.

@callmephil

This comment has been minimized.

Copy link

@callmephil callmephil commented Oct 17, 2019

Node.js & ES6

get days diff between two dates and output all weekdays in between including start and end dates.
return an array of dates.

const moment = require("moment");
const getDatesDiff = (start_date, end_date, date_format = "YYYY-MM-DD") => {
  const getDateAsArray = date => {
    return moment(date.split(/\D+/), date_format);
  };
  const diff = getDateAsArray(end_date).diff(getDateAsArray(start_date), "days") + 1;
  const dates = [];
  for (let i = 0; i < diff; i++) {
    const nextDate = getDateAsArray(start_date).add(i, "day");
    const isWeekEndDay = nextDate.isoWeekday() > 5;
    if (!isWeekEndDay)
      dates.push(nextDate.format(date_format))
  }
  return dates;
};

Use:

const date_log = getDaysDiff ('2019-10-17',  '2019-10-25');
console.log(date_log);

output:

date_log = 
[ '2019-10-17',
  '2019-10-18',
  '2019-10-21',
  '2019-10-22',
  '2019-10-23',
  '2019-10-24',
  '2019-10-25'
]
@dunghoang74

This comment has been minimized.

Copy link

@dunghoang74 dunghoang74 commented Dec 11, 2019

I tried this and it was returned wrong
getDates(new Date(2019,12,22), new Date(2020,1,7));

Wed Jan 22 2020 00:00:00 GMT+0700 (Indochina Time)
Thu Jan 23 2020 00:00:00 GMT+0700 (Indochina Time)
Jan 24 2020 00:00:00 GMT+0700 (Indochina Time)
Sat Jan 25 2020 00:00:00 GMT+0700 (Indochina Time)
Sun Jan 26 2020 00:00:00 GMT+0700 (Indochina Time)
Mon Jan 27 2020 00:00:00 GMT+0700 (Indochina Time)
Tue Jan 28 2020 00:00:00 GMT+0700 (Indochina Time)
Wed Jan 29 2020 00:00:00 GMT+0700 (Indochina Time)
Thu Jan 30 2020 00:00:00 GMT+0700 (Indochina Time)
Fri Jan 31 2020 00:00:00 GMT+0700 (Indochina Time)
Sat Feb 01 2020 00:00:00 GMT+0700 (Indochina Time)
Sun Feb 02 2020 00:00:00 GMT+0700 (Indochina Time)
Mon Feb 03 2020 00:00:00 GMT+0700 (Indochina Time)
Tue Feb 04 2020 00:00:00 GMT+0700 (Indochina Time)
Wed Feb 05 2020 00:00:00 GMT+0700 (Indochina Time)
Thu Feb 06 2020 00:00:00 GMT+0700 (Indochina Time)
Fri Feb 07 2020 00:00:00 GMT+0700 (Indochina Time)
@Muhammad-Wasi

This comment has been minimized.

Copy link

@Muhammad-Wasi Muhammad-Wasi commented Feb 11, 2020

Thanks for the code.

@anoop0567

This comment has been minimized.

Copy link

@anoop0567 anoop0567 commented Feb 25, 2020

Please provide code for getting hours in between two dates with JavaScript.

Example

let date1 = new Date(1582545600000) // 24th Feb 17:30
let date2 = new Date(1582574400000) // 25th Feb 01:30
getHourWiseDates(date1, date2);

Output
[ { start_hour: 1582545600000 // 24th Feb 17:30 end_hour: 1582547399099 // 24th Feb 17:59 }, { start_hour: 1582547400000 // 24th Feb 18:00 end_hour: 1582550999099 // 24th Feb 18:59 } ... ... ... { start_hour: 1582572600000 //25th Feb 01:00 end_hour: 1582574400000 // 25th Feb 01:30 } ]

@kuldeep-pixer

This comment has been minimized.

Copy link

@kuldeep-pixer kuldeep-pixer commented Oct 21, 2020

Screenshot_1

i want this type of array like shortmonths name and years starting date is Sep 2017 to current months and year

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment