views:

22

answers:

2

I'm looking for a js (or jQuery) function where I pass a start date and end date, and the function returns on inclusive list (array or object) of each date in that range.

For example, if I pass this function a date object for 2010-08-31 and for 2010-09-02, then the function should return: 2010-08-31 2010-09-01 2010-09-02

Anyone have a function that does that or know of a jQuery plugin that would include this functionality?

+1  A: 

It sounds like you might want to use Datejs. It is extremely awesome.


If you use Datejs, here's how you could do it:

function expandRange(start, end) // start and end are your two Date inputs
{
    var range;
    if (start.isBefore(end))
    {
        start = start.clone();
        range = [];

        while (!start.same().day(end))
        {
            range.push(start.clone());
            start.addDays(1);
        }
        range.push(end.clone());

        return range;
    }
    else
    {
        // arguments were passed in wrong order
        return expandRange(end, start);
    }
}

ex. for me:

expandRange(new Date('2010-08-31'), new Date('2010-09-02'));

returns an array with 3 Date objects:

[Tue Aug 31 2010 00:00:00 GMT-0400 (Eastern Daylight Time),
 Wed Sep 01 2010 00:00:00 GMT-0400 (Eastern Daylight Time),
 Thu Sep 02 2010 00:00:00 GMT-0400 (Eastern Daylight Time)]
Matt Ball
A: 

No pre-defined method of which I know, but you can implement it like:

function DatesInRange(dStrStart, dStrEnd) {
    var dStart = new Date(dStrStart);
    var dEnd = new Date(dStrEnd);

    var aDates = [];
    aDates.push(dStart);

    if(dStart <= dEnd) {
        for(var d = dStart; d <= dEnd; d.setDate(d.getDate() + 1)) {
            aDates.push(d);
        }
    }

    return aDates;
}

You'll have to add the input sanitization/error checking (ensuring that the Date strings parse to actual dates, etc.).

palswim