Get a list of dates within a range using javascript

I am looking for a js (or jQuery) function in which I pass in a start date and an end date, and the function returns an inclusive list (array or object) of each date in this range.

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

Does anyone have a function that does this or knows a jQuery plugin that will enable this functionality?

+3
source share
2 answers

It looks like you can use Datejs . This is amazing.


If you are using Datejs, here is 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'));

3 Date:

[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)]
+4

, , :

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;
}

/ ( ..).

+1

Source: https://habr.com/ru/post/1765880/


All Articles