Search code examples
javascriptarraysecmascript-6date-comparisondatetime-comparison

compare an array of dates to check date overlap in an easy way in java-script


I would like to check any date conflicts occurring in my date array. I have an array like this.

[['2020-07-03T18:30:00.125000Z','2020-07-04T01:30:00Z'],['2020-07-03T18:30:00.125000Z','2020-07-04T00:30:00Z'],['2020-07-03T18:30:00.125000Z','2020-07-04T00:30:00Z']]

The first date in individual array is start date and end date respectively. What I want to check here is, the first array date is conflicting with the following dates in the array. So that I can assign a person based on the date. One person can assign to a single date time. So anybody knows the perfect ES6 way to solve this?


Solution

  • I have created a function to solve this question. dateTimes is the array which contains the dates.

    checkDateTimeOverlap = (dateTimes)=>{
            let isOverlap = false;
            dateTimes.forEach((time,i) => {
                let  st1 = time[0];
                let  et1 = time[1];
              
                dateTimes.forEach((time2,j) => {               
                    if(i != j){
                        let st2 = time2[0];
                        let et2 = time2[1];
                        if (st1 >= st2 && st1 <= et2 || et1 >= st2 && et1 <= et2 || st2 >= st1 && st2 <= et1 || et2 >= st1 && et2 <= et1) {
                            isOverlap =  true;
                        }else{
                            isOverlap =  false;
                        }
                    }
                })
            }); 
    
            return isOverlap;
        }