-2

I have an enrolment project and user get subject on the list. Now how to check the time is conflicting with others? The variables are strings and my teacher wants that format only.

var time1 = '10:00:AM-12:00:PM';

var time2 = '10:30:AM-11:00:AM';

How can I check the time2 is conflicting with time1? Is there a jquery library that might be helpful?

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Goper Leo Zosa
  • 1,185
  • 3
  • 15
  • 33

3 Answers3

3

What I would do, is create a function for splitting these strings into a multi-dimensional array :

var timeSegments = function(time) {
   var timeArray = time.split("-");
   for(i = 0; i < timeArray.length; i++) {
       timeArray[i] = timeArray[i].split(":");
   }
   return timeArray;
}

Then, I'd run that function for both time segments :

time1 = timeSegments('10:00:AM-12:00:PM');
time2 = timeSegments('10:30:AM-11:00:AM');

The output for time1 should be :

[
    [
        0: "10"
        1: "00"
        2: "AM"
    ], [
        0: "12"
        1: "00"
        2: "PM"
    ]
]

The output for time2 should be :

[
    [
        0: "10"
        1: "30"
        2: "AM"
    ], [
        0: "11"
        1: "00"
        2: "AM"
    ]
]

You can now compare both time segments by comparing the values in these arrays.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
0

Convert both start times and end times to dates, then check if end time of time2 is later than start time of time1 and vice versa. If both end times are later than the other's start time, you have conflicting time ranges. Converting strings to dates is easier done via moment.js.

Community
  • 1
  • 1
Johannes Jander
  • 4,974
  • 2
  • 31
  • 46
0

Convert your times to numbers and compare:

var time1 = '10:00:AM-12:00:PM';
var time2 = '10:30:AM-11:00:AM';
var convertedTime1 = getConvertedStartEndTime(time1)
var convertedTime2 = getConvertedStartEndTime(time2)


function getConvertedStartEndTime(time){
    time = time.split('-').map(function(item){ return item.replace('PM', '10000').replace('AM', 1)});
    time = time.map(function(item){ return item.split(':')});
    var time2StartConverted = time[0].reduce(function (a, b) {
    return parseInt(a) + parseInt(b);
    });
    var time2EndConverted = time[1].reduce(function (a, b) {
        return parseInt(a) + parseInt(b);
    });
    return [time2StartConverted, time2EndConverted]
}

Know you could perform comparing between dates

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82