Start and end date on multiple dates range
Hi my problem is 开发者_开发技巧somewhat special or maybe not. However the problem is that I parse range of dates in one array, where I need to find start date and end date where ever it may occur in ranges. I do not know did I explain this well but if you need more info, please let me know.
e.g. [2010-7-11,2010-7-12,2010-7-13, 2010-9-01, 2010-9-02,....]
Now
2010-7-11 start and 2010-7-13 end
2010-9-01 start 2010-9-02 end
So on for entire ranges within array
Thanks in advance
Here's something quick and dirty. It expects the dates
array to already be sorted in ascending order.
var dates = ["2010-7-11", "2010-7-12", "2010-7-13", "2010-9-01", "2010-9-02"],
startDates = [], endDates = [],
lastDate = null, date = null;
for ( var i=0, l=dates.length; i<l; ++i ) {
date = new Date(dates[i].replace(/-/g, "/"));
//
if ( !lastDate ) {
startDates.push(lastDate = date);
}
// If the diffrence between the days is greater than the number
// of milliseconds in a day, then it is not consecutive
else if ( date - lastDate > 86400000 ) {
lastDate = null;
endDates.push(date);
}
}
// Close the last range
endDates.push(date);
// Result is two symetical arrays
console.log(startDates, endDates);
精彩评论