How to check if times overlap using moment and JavaScript?

Sometimes, we want to check if times overlap using moment and JavaScript.

In this article, we’ll look at how to check if times overlap using moment and JavaScript.

How to check if times overlap using moment and JavaScript?

To check if times overlap using moment and JavaScript, we can use the moment-range plugin.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/4.0.2/moment-range.js"></script>

to add the moment and moment-range scripts.

Then we write:

window['moment-range'].extendMoment(moment);

const start = new Date(2022, 0, 15);
const end = new Date(2022, 4, 23);
const range = moment.range(start, end);

const a = new Date(2022, 1, 15);
const b = new Date(2021, 1, 15);
console.log(range.contains(a))
console.log(range.contains(b))

to add moment-range with

window['moment-range'].extendMoment(moment)

Then we create a moment-range object with moment.range and 2 dates.

Next, we check if dates a and b are in the range by calling range.contains.

Therefore, the first log is true and the 2nd is false since a is in the range and b isn’t.

Conclusion

To check if times overlap using moment and JavaScript, we can use the moment-range plugin.