6

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

2
  • 6
    Months are numbered from 0 in JavaScript dates. Month 02 is March, not February.
    – Pointy
    Commented Oct 2, 2014 at 15:15
  • this solved my issue Thanks @Pointy Commented Sep 25, 2020 at 7:16

7 Answers 7

13
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);
};
2
  • 2
    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
    – koceeng
    Commented Mar 2, 2017 at 3:53
  • Excellent Answer. Commented Jun 11, 2019 at 6:58
3

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

3

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

0
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;
  }
0
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);
        }
2
  • Welcome to StackOverflow. Try to explain more clearly why this is an answer to the question. Commented Sep 25, 2019 at 18:45
  • Code-only answers are generally frowned upon on this site. Could you please edit your answer to include some comments or explanation of your code? Explanations should answer questions like: What does it do? How does it do it? Where does it go? How does it solve OP's problem? See: How to anwser. Thanks! Commented Sep 25, 2019 at 18:46
0

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.

-1

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
]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.