While working on custom calendar, I can\'t figure out how to find time slots that overlaps any other time slot.
Time slots start from 0 to 720 (9am to 9pm with each
To me it is easier to use timestamps for each start and end event, that way you can work with them directly or change them to date objects. To get the value, create a date object for each start and end, then:
var a.start = startDate.getTime();
var a.end = endDate.getTime();
For overlap:
if (a.start <= b.start && a.end > b.start ||
a.start < b.end && a.end >= b.end) {
// a overlaps b
}
You can leave them as date objects if you like, the above will work just as well.
Ok here's a working example:
Assuming a nominal date of 2012-05-15, then the events array looks like:
// Use iso8601 like datestring to make a local date object
function getDateObj(s) {
var bits = s.split(/[- :]/);
var date = new Date(bits[0], bits[1] - 1, bits[2]);
date.setHours(bits[3], bits[4], 0);
return date;
}
var events = [
{id: 1, start: getDateObj('2012-05-15 09:00'), end: getDateObj('2012-05-15 09:30')},
{id: 2, start: getDateObj('2012-05-15 09:30'), end: getDateObj('2012-05-15 11:30')},
{id: 3, start: getDateObj('2012-05-15 09:20'), end: getDateObj('2012-05-15 12:00')},
{id: 4, start: getDateObj('2012-05-15 12:20'), end: getDateObj('2012-05-15 12:30')},
{id: 5, start: getDateObj('2012-05-15 18:00'), end: getDateObj('2012-05-15 19:00')},
{id: 6, start: getDateObj('2012-05-15 18:20'), end: getDateObj('2012-05-15 19:20')}
];
function getOverlappingEvents(eventArray) {
var result = [];
var a, b;
// Sort the event array on start time
eventArray.sort(function(a, b) {
return a.start - b.start;
});
// Get overlapping events
for (var i=0, iLen=eventArray.length - 1; i b.start) ||
(a.start < b.end && a.end >= b.end) ) {
result.push([a.id, b.id]);
}
}
return result;
}
// Run it
alert(getOverlappingEvents(events).join('\n')); // 1,3 2,3 5,6