rargy
rargy

Reputation: 129

JS - How to match overlapping time ranges?

I'm trying to build a custom filter in Javascript, I'm trying to return true/match two time ranges formatted in the millisecond getTime() format. The first time range is from an object. The Second time range is from a users input specifying the time to be filtered. Currently my code matches when the second time range falls between the min and max values of the first time range, but I would like it so that it will match if there is any overlap between the time ranges at all.

JS:

                var filter_from = new Date();
                filter_from.setHours(this.availability_from.split(/:/)[0]);
                filter_from.setMinutes(this.availability_from.split(/:/)[1]);
                filter_from = filter_from.getTime();

                var filter_to = new Date();
                filter_to.setHours(this.availability_from.split(/:/)[0]);
                filter_to.setMinutes(this.availability_from.split(/:/)[1]);
                filter_to = filter_to.getTime();

                var a_from = new Date();
                a_from.setHours((hits[i].availability.split("-")[0]).split(":")[0]);
                a_from.setMinutes((hits[i].availability.split("-")[0]).split(":")[1]);
                a_from = a_from.getTime();

                var a_to = new Date();
                a_to.setHours((hits[i].availability.split("-")[1]).split(":")[0])
                a_to.setMinutes((hits[i].availability.split("-")[1]).split(":")[1])
                a_to = a_to.getTime();



                if (Math.min(filter_from, filter_to) <= Math.max(a_from, a_to) && Math.max(filter_from, filter_to) >= Math.min(a_from, a_to)) {
                    console.log("matched");
                }

Any help would be amazing, It's confusing me alot, thankyou! :)

Upvotes: 1

Views: 216

Answers (1)

tevemadar
tevemadar

Reputation: 13225

There is an overlap when any of the endpoints fall between the endpoints of the other interval.

if(  (filter_from < a_from && a_from < filter_to)
  || (filter_from < a_to   &&   a_to < filter_to)
  || (a_from < filter_from && filter_from < a_to)
  || (a_from < filter_to   &&   filter_to < a_to))

Upvotes: 2

Related Questions