Oshan Wisumperuma
Oshan Wisumperuma

Reputation: 1948

Get a list of dates between two dates using javascript

From JavaScript is there a way to get list of days between two dates from MySQL format. I don't want to use any library for this. This is what i did.

function generateDateList(from, to) {

    var getDate = function(date) { //Mysql Format
        var m = date.getMonth(), d = date.getDate();
        return date.getFullYear() + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d);
    }
    var fs = from.split('-'), startDate = new Date(fs[0], fs[1], fs[2]), result = [getDate(startDate)], start = startDate.getTime(), ts, end;

    if ( typeof to == 'undefined') {
        end = new Date().getTime();
    } else {
        ts = to.split('-');
        end = new Date(ts[0], ts[1], ts[2]).getTime();
    }
    while (start < end) {
        start += 86400000;
        startDate.setTime(start);
        result.push(getDate(startDate));
    }
    return result;
}

console.log(generateDateList('2014-2-27', '2014-3-2'));

I test it from chrome and nodejs below are the result.

[ '2014-02-27',
  '2014-02-28',
  '2014-02-29',
  '2014-02-30',
  '2014-02-31',
  '2014-03-01',
  '2014-03-02' ]

yeh big leap year:-D..., how can i fix this? or is there any better way.?

Upvotes: 6

Views: 21281

Answers (7)

Rafiq
Rafiq

Reputation: 11465

if you have a large gap between the start and end date then using moment can be vital

var moment = require('moment');

function getDates(fromDate, toDate) {
  const dateArray = [];
  let currentDate = moment(fromDate);
  const endDate = moment(toDate);
  while (currentDate <= endDate) {
    dateArray.push({
      date: moment(currentDate).format('YYYY-MM-DD'),
      month: moment(currentDate).month(),
      day: moment(currentDate).day(),
    });
    currentDate = moment(currentDate).add(1, 'days');
  }
  return dateArray;
}

console.log(getDates(new Date('2018-01-01'), new Date('2028-07-01')));

output:

[
  { date: '2018-01-01', month: 0, day: 1 },
  { date: '2018-01-02', month: 0, day: 2 },
  { date: '2018-01-03', month: 0, day: 3 },
  { date: '2018-01-04', month: 0, day: 4 },
  { date: '2018-01-05', month: 0, day: 5 },
  { date: '2018-01-06', month: 0, day: 6 },
  { date: '2018-01-07', month: 0, day: 0 },
  { date: '2018-01-08', month: 0, day: 1 },
  ... 3765 more items
]

Upvotes: -1

C&#244;ng Thắng
C&#244;ng Thắng

Reputation: 285

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

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

Upvotes: 13

stayingcool
stayingcool

Reputation: 2814

I have used this one from https://flaviocopes.com/how-to-get-days-between-dates-javascript/

const getDatesBetweenDates = (startDate, endDate) => {
  let dates = []
  //to avoid modifying the original date
  const theDate = new Date(startDate)
  while (theDate < new Date(endDate)) {
    dates = [...dates, new Date(theDate)]
    theDate.setDate(theDate.getDate() + 1)
  }
  dates = [...dates, new Date(endDate)]
  return dates
}

Invoke the function as follows:

getDatesBetweenDates("2021-12-28", "2021-03-01")

Note - I just had to fix issues with the Date object creation (new Date()) in the while loop and in the dates array. Other than that the code is pretty much same as seen on the above link

Upvotes: 3

Seb
Seb

Reputation: 5842

I expanded Công Thắng's great answer to return {years, months, days}, thought it was worth sharing:

function getDates(startDate, endDate) {
  const days = [],  
        months = new Set(),
        years = new Set()

  const dateMove = new Date(startDate)
  let date = startDate

  while (date < endDate){
    date = dateMove.toISOString().slice(0,10)
    months.add(date.slice(0, 7))
    years.add(date.slice(0, 4))
    days.push(date)
    dateMove.setDate(dateMove.getDate()+1) // increment day
  }
  return {years: [...years], months: [...months], days} // return arrays
}

console.log(getDates('2016-02-28', '2016-03-01')) // leap year
/* =>
 {
    years: [ '2016' ],
    months: [ '2016-02', '2016-03' ],
    days: [ '2016-02-28', '2016-02-29', '2016-03-01' ]
  }
*/
const {months} = getDates('2016-02-28', '2016-03-01') // get only months

Basically the function just increments the built-in Date object by one day from start to end, while the Sets capture unique months and years.

Upvotes: 0

Blitz
Blitz

Reputation: 500

Take the start date and increment it by one day until you reach the end date.

Note: MySQL dates are standard format, no need to parse it by hand just pass it to the Date constructor: new Date('2008-06-13').

const addDays = (date, days = 1) => {
  const result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
};

const dateRange = (start, end, range = []) => {
  if (start > end) return range;
  const next = addDays(start, 1);
  return dateRange(next, end, [...range, start]);
};

const range = dateRange(new Date("2014-02-27"), new Date("2014-03-02"));

console.log(range);
console.log(range.map(date => date.toISOString().slice(0, 10)))

Here I use a recursive function, but you could achieve the same thing using a while (see other answers).

Upvotes: 3

Jairo W Gonzalez
Jairo W Gonzalez

Reputation: 1

var oDate1 = oEvent.getParameter("from"),
    oDate2 = oEvent.getParameter("to");

        var aDates = [];
        var currentDate = oDate1;
        while (currentDate <= oDate2) {
            aDates.push(new Date(currentDate));
            currentDate.setDate(currentDate.getDate() + 1);
        }

Upvotes: 0

holla
holla

Reputation: 161

dateRange(startDate, endDate) {
    var start      = startDate.split('-');
    var end        = endDate.split('-');
    var startYear  = parseInt(start[0]);
    var endYear    = parseInt(end[0]);
    var dates      = [];

    for(var i = startYear; i <= endYear; i++) {
      var endMonth = i != endYear ? 11 : parseInt(end[1]) - 1;
      var startMon = i === startYear ? parseInt(start[1])-1 : 0;
      for(var j = startMon; j <= endMonth; j = j > 12 ? j % 12 || 11 : j+1) {
        var month = j+1;
        var displayMonth = month < 10 ? '0'+month : month;
        dates.push([i, displayMonth, '01'].join('-'));
      }
    }
    return dates;
  }

Upvotes: 0

Related Questions