javascriptangularjsdatetimemomentjsangular-moment

Use JavaScript to compare time ranges


I have a collection of time ranges in the form of Date objects. I need to compare those time ranges against a new time range to make sure I don't add a time range that overlaps or duplicates an existing time range.

Here's an example of the collection.

var timeSlots = [
    {
        BeginTime: new Date("10/25/2015 8:00 AM"),
        EndTime: new Date("10/25/2015 8:45 AM")
    },
    {
        BeginTime: new Date("10/25/2015 9:00 AM"),
        EndTime: new Date("10/25/2015 9:45 AM")
    },
    {
        BeginTime: new Date("10/25/2015 9:50 AM"),
        EndTime: new Date("10/25/2015 10:30 AM")
    }
];

In the previous example, the date part of the dates don't matter. The times do.

If I have an new time range object that begins at 9:30 AM, I need to be able to detect that.

This is inside of an AngularJS app and it has access to both MomentJS and Angular Moment.

How can I take a new time slot object and ensure that it won't conflict with the others that exist?

// building off of the previous example
var newTimeSlot = newDate("10/25/2015 9:00 AM");
if (!conflictingTime(newTimeSlot)) {
    // then run my code
}

function conflictingTime(time) {
    // how do I do this?
}

Solution

  • Since this is for an open source project, I was hoping that someone here likes SO points enough to come up with a more "best practice" or more elegant solution than what I did. I guess everyone in the comments hates SO points though.

    So here's my solution.

    angular.forEach($scope.timeSlots, function (timeSlot, index) {
        var beginTimeHasIssue = ($scope.timeSlot.BeginTime >= timeSlot.BeginTime && $scope.timeSlot.BeginTime <= timeSlot.EndTime);
        var endTimeHasIssue = ($scope.timeSlot.EndTime >= timeSlot.BeginTime && $scope.timeSlot.EndTime <= timeSlot.EndTime);
    
        if (beginTimeHasIssue || endTimeHasIssue) {
            hasError = true;
            $scope.HasTimeSlotError = true;
            return;
        } 
    });