Categories
JavaScript Answers

How to check if one date is between two dates with JavaScript?

Spread the love

Sometimes, we want to check if one date is between two dates with JavaScript.

In this article, we’ll look at how to check if one date is between two dates with JavaScript.

How to check if one date is between two dates with JavaScript?

To check if one date is between two dates with JavaScript, we can compare their timestamps.

For instance, we write

const currentDate = new Date().toJSON().slice(0, 10);
const from = new Date("2022/01/01");
const to = new Date("2022/01/31");
const check = new Date(currentDate);

console.log(check > from && check < to);

to get the currentDate date string with the new Date().toJSON().slice(0, 10).

Then we create the from and to dates with the Date constructor.

We then create check Date object with the currentDate string.

Then we check if check is between from and to with

check > from && check < to

When we use comparison operators with dates, they’ll be converted to timestamps in milliseconds before we compare them, so we can compare them directly.

Conclusion

To check if one date is between two dates with JavaScript, we can compare their timestamps.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *