Asynchronous
Asynchronous

Reputation: 3977

Getting dates between two dates returing wrong dates outside of specified date range

I have the following code which returns date between two given dates, however, I am getting dates outside of the specified range.

I need to return formatted strings like: 12/01/2015or 01/01/2015. Note the added leading zeros. If I enter a Date range like: 12/01/2015 - 01/31/2016, I get a date beginning 11/01/2015.

How do I get only the code within the given rage?

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(('0' + currentDate.getMonth()+ 1 ).slice(-2) + '/' + 
            ('0' + currentDate.getDate()).slice(-2) + '/' + currentDate.getFullYear());
        currentDate = addDays.call(currentDate, 1);
    }

    return dates;
};

Upvotes: 0

Views: 62

Answers (2)

birwin
birwin

Reputation: 2684

You could use the moment library (http://momentjs.com). In that case, this function becomes something like...

var start = moment('2015-12-01');
var end = moment('2016-01-01');

var getDates = function(start, end) {
    var dates = [];
    while (start <= end) {
        dates.push(start.format('MM/DD/YYYY'));
        start.add(1, 'd');
    }
    return dates;
}

var dates = getDates(start, end);

console.log(dates);

Upvotes: 1

void
void

Reputation: 36703

Change this line

dates.push(('0' + currentDate.getMonth()+ 1 ).slice(-2) + '/' + 
                ('0' + currentDate.getDate()).slice(-2) + '/' + currentDate.getFullYear());

to

dates.push(('0' + (currentDate.getMonth() + 1)).slice(-2) + '/' +
      ('0' + currentDate.getDate()).slice(-2) + '/' + currentDate.getFullYear());

First add 1 then prepend 0 and then slice.

Also you need to parse the startDate and endDate as dates using new Date();

Complete Code should be like:

var getDates = function(startDate, endDate) {
  var dates = [],
    currentDate = new Date(startDate),
    endDate = new Date(endDate),
    addDays = function(days) {
      var date = new Date(this.valueOf());
      date.setDate(date.getDate() + days);
      return date;
    };
  while (currentDate <= endDate) {
    dates.push(('0' + (currentDate.getMonth() + 1)).slice(-2) + '/' +
      ('0' + currentDate.getDate()).slice(-2) + '/' + currentDate.getFullYear());

    currentDate = addDays.call(currentDate, 1);
  }

  return dates;
};

console.log(getDates("12/06/2015", "01/31/2016"));

WORKING FIDDLE

Upvotes: 1

Related Questions