JavaScript - Matching overlapping time intervals

Struggling to develop a custom filter using Javascript, I aim to determine if two time ranges in millisecond getTime() format match. The first time range is retrieved from an object while the second comes from user input for filtering. Currently, my code checks if the second time range falls within the min and max values of the first time range. However, I want it to detect any overlap between the time ranges.

Javascript:

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");
}

Would greatly appreciate any assistance with this perplexing challenge, thank you! :)

Answer №1

If any of the endpoints of one interval fall between the endpoints of another interval, there is an overlap.

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))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Access a document from a collaborative directory directly in a web browser

When I paste the shared path for a PDF file into the address bar, it opens perfectly in all browsers. The code below works fine in IE 8 but not in Chrome and Firefox. Code: function openPDF(file) { window.open(file, '_blank'); } function link ...

How can I pass an argument to Node within a package.json script instead of the script itself?

In my project's package.json, I have a script that looks like this: "scripts": { "test": "... && mocha --full-trace test/db test/http test/storage test/utils", I am trying to pass the --async-stack-traces o ...

Performing an Ajax request to submit a form without the need to reload the page in MVC

I am looking for assistance with submitting a form from an MVC view without refreshing the page. However, it seems that my AJAX code below is not functioning properly: //here is ajax call function AjaxCallAndShowMessage(btnClick) { $('form').s ...

Vue.js - Displaying validation errors when a user interacts outside of a component

The ExamEditor Vue component I am working on is quite complex, consisting of sub-components like QuestionEditor and ExerciseEditor. These components are all tied to an exam object that contains nested arrays with questions and more. The layout inside the e ...

Challenges with Scaling HTML5 Video onto Canvas

Attempting to extract a frame from an html5 video to generate a thumbnail, but encountering peculiar outcomes when the image is rendered onto canvas. The issue lies in the fact that the canvas displays only a greatly magnified portion of the video! Refer ...

What is the best way to change a JavaScript variable into a PHP variable?

I am interested in converting my JavaScript variable to a PHP variable... Currently, I have the following scenario - in the code below there is a variable e, but I would like to utilize e in PHP as $e: <script> function test() { var e = documen ...

Determining button click events in VueJS using the Watch method

Creating a feature for undo/redo in VueJS involves watching the settings and adding a new element to an array of changes when there is a setting change. Additionally, there is a method for undoing actions when the corresponding button is clicked. An issue ...

Adjusting Javascript code to launch a URL in a new window or new tab depending on the user's selection

I seem to be encountering a puzzling issue with a link on my website. When clicked normally, the link opens in a new window. However, if I right-click and select "open in new window" or "open in new tab," it just reloads the same page where the link was cl ...

Error: unable to access response.data due to its undefined value

I've encountered an issue with the promise response while using a vForm PUT request to UPDATE a model in Laravel backend. Although the response code is 200 (OK, updated) and the model is successfully updated, I'm facing an error specifically wit ...

Send information as FormData object

I'm getting the data in this format: pert_submit: {systemId: "53183", pert-id: "176061", score: 0, q2c: "3\0", q2t: "", …} Now I need to send it as FormData in my post request. Since I can't use an ...

React SlideMenu will not close when a link is clicked

I am facing an issue with my off-canvas menu, which slides in when the variable isOpen is set to true. However, the problem arises when trying to slide it back out upon clicking a Link to navigate to another page. Instead of sliding out, the mobile menu oc ...

Having trouble receiving a response when making a request to an API

I encountered an issue while trying to fetch an API. Initially, I received an error message stating that the message port was closed before a response was received. After removing all extensions, the error disappeared but now I am still unable to receive a ...

Error 400: The onCreate Trigger function for Cloud functions is experiencing issues with HTTP requests due to errors in the request

I am encountering an issue when attempting to add a trigger for Firestore OnCreate, as the deployment fails with HTTP Error: 400 stating that the request has errors. Essentially, my goal is to write to a new document if a record is created in a different ...

What could be causing my select value to stay unchanged? Issue with the "selected" attribute or property

var original_role = $('option:selected', '#user_role').val(); $('#role_cancel').click(function() { //console.log(original_role); $('option:selected', '#user_role').removeAttr('selected'); //des ...

Exploring various layers of nested data

I am currently developing a comprehensive global data storage system for my application (specifically an Angular JS app - although this question pertains to JavaScript in general). I have established a 'service' that is responsible for setting t ...

Obtaining a subset of data from firebase

I am currently working on retrieving a sub-collection from the Firestore database using Angular. In my database, I have a collection called 'Company' which contains fields for 'Name' and 'Id', as well as a sub-collection named ...

Issue with triggering ReactJS onClick function accurately

For the function to work correctly, I had to add e.preventDefault(). However, my goal is for it to redirect the user to '/' after submitting the form. Below is the function that I am attempting to trigger: onAddPoints = (e) => { e.prevent ...

Issue with Vue: After removing an item from a v-for list, there is a remnant

Can you help me solve this issue with my Vue component setup? I have a list of components, each consisting of a preview canvas, a name, and a delete button. These components are stored in Vuex. For example, the list could look like this: | [W] Item 1 ...

When implementing useFetch with onMounted in Nuxt3, data is not being fetched upon directly opening the link

In my project, I have implemented the useFetch function in the composition api to fetch data. The function is then called within the onMounted hook of components. Here is how it's done: Custom Composable: useShows.ts export function useShows(){ ...

The JSON page does not display the image

I am facing an issue where the images are not displaying on both the JSON page and the HTML page, even though the image source name is being outputted. How can I ensure that the images show up on the HTML page? Thank you for taking the time to help. line ...