0

I want to list all dates between 2 dates like..

list_dates('06/27/2013','07/31/2013');

This function will return all dates between 06/27/2013 - 07/31/2013 in array like..

['06/27/2013','06/28/2013','06/29/2013','06/30/2013','07/01/2013','...so_on..','07/31/2013'];

This function will work in all cases , Like older to newer , newer to older , or same dates like..

list_dates('06/27/2013','07/31/2013');
list_dates('07/31/2013','06/27/2013');
list_dates('07/31/2013','07/31/2013');

I do like...

function list_dates(a,b) {
    var list = [];
    var a_date = new Date(a);
    var b_date = new Date(b);

    if         (a_date > b_date) {

    } else if  (a_date < b_date) {

    } else {
        list.push(a);
    }

    return list;
}

Demo : http://jsfiddle.net/fSGQ6/

But how to get dates between 2 dates ?

4

3 回答 3

3

try this

list_dates('11/27/2013', '12/31/2013');
list_dates('03/21/2013', '02/14/2013');
list_dates('07/31/2013', '07/31/2013');

function list_dates(a, b) {
    var list = [];
    var a_date = new Date(a);
    var b_date = new Date(b);

    if (a_date > b_date) {
        while (a_date >= b_date) {

            var date_format = ('0' + (b_date.getMonth() + 1)).slice(-2) + '/' + ('0' + b_date.getDate()).slice(-2) + '/' + b_date.getFullYear();
            list.push(date_format);
            b_date = new Date(b_date.setDate(b_date.getDate() + 1));
        }
    } else if (a_date < b_date) {
        while (b_date >= a_date) {

            var date_format = ('0' + (a_date.getMonth() + 1)).slice(-2) + '/' + ('0' + a_date.getDate()).slice(-2) + '/' + a_date.getFullYear();
            list.push(date_format);
            a_date = new Date(a_date.setDate(a_date.getDate() + 1));
        }
    } else {
        list.push(a);
    }

    console.log(list);
}

UPDATE: as poster requirement

于 2013-06-27T09:05:38.933 回答
2
var start = new Date(2013,06,27);
var end = new Date(2013,07,31);
var result =[];
var loop = true;

while(loop){
  console.log(start.toISOString);
  result.push(start);

  start.setDate(start.getDate()+1)
  if(start>end){
    loop = false;
  }
}
于 2013-06-27T09:02:44.367 回答
1
Date.prototype.getShortDate = function () {
    // Do formatting of string here
    return (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear();
}

function list_dates(a, b) {

    var a_date = new Date(a),
        b_date = new Date(b),
        list = [a_date.getShortDate()],
        change = (a_date > b_date ? -1 : 1);

    while (a_date.getTime() != b_date.getTime()) {
        a_date.setDate(a_date.getDate() + change);
        list.push(a_date.getShortDate());
    }

    return list;
}
于 2013-06-27T09:40:59.817 回答