Skip to content

Instantly share code, notes, and snippets.

@timkendall
Created October 25, 2014 04:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timkendall/75474b36916696bbd606 to your computer and use it in GitHub Desktop.
Save timkendall/75474b36916696bbd606 to your computer and use it in GitHub Desktop.
Naive Timespan class (doesn't account for multiple days)
function Timespan (start, end) {
/*
* Todo - handle multiday timespans
*/
// Make sure times are valid times
if (!Time.isValid(start) || !Time.isValid(end)) throw new Error('Invalid start or end times');
// Normalize format ex.'02:15 PM'
this.start = new Time(start).format('hh:mm AM');
this.end = new Time(end).format('hh:mm AM')
var self = this;
var convertToDateTime = function (time) {
// Assuming this format ex.'02:15 PM' for time
var hour = parseInt(time.substring(0, time.indexOf(':'))),
minutes = parseInt(time.substring(time.indexOf(':')+1, time.indexOf(' ')));
// Handle PM
var period = time.substring(time.indexOf(' ') + 1, time.length);
if (period === 'PM') hour += 12;
return new Date('2014','10','24', hour.toString(), minutes.toString()).getTime();
}
this.overlaps = function (timespanB) {
// Convert times to Date() times
var startA = convertToDateTime(self.start),
endA = convertToDateTime(self.end),
startB = convertToDateTime(timespanB.start),
endB = convertToDateTime(timespanB.end);
if (startA >= endB) return false; // A range completely after B
else if (endA <= startB) return false; // A range completely before B
else return true; // Overlap
}
}
var ts1 = new Timespan('8pm', '8:50pm'),
ts2 = new Timespan('8pm', '10:50pm');
console.log('Overlap?: ' + ts1.overlaps(ts2));
@timkendall
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment