Get list of dates within a span with javascript
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开发者_Python百科-09-02
Anyone have a function that does that or know of a jQuery plugin that would include this functionality?
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)]
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.).
精彩评论