Created
October 25, 2014 04:41
-
-
Save timkendall/75474b36916696bbd606 to your computer and use it in GitHub Desktop.
Naive Timespan class (doesn't account for multiple days)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires https://github.com/zever/time