Categories
JavaScript Answers

How to check if the time is between 7pm and 7am and do something with JavaScript?

Spread the love

Sometimes, we want to check if the time is between 7pm and 7am and do something with JavaScript.

In this article, we’ll look at how to check if the time is between 7pm and 7am and do something with JavaScript.

How to check if the time is between 7pm and 7am and do something with JavaScript?

To check if the time is between 7pm and 7am and do something with JavaScript, we can use the date’s getHours method to get the time.

For instance, we write:

const today = new Date().getHours();
if (today >= 7 && today <= 19) {
  document.body.style.background = "green";
} else {
  document.body.style.background = "blue";
}

to get the hour of the day with getHours.

Then we get if the time is between 7am and 7pm with today >= 7 && today <= 19.

And we set the background to green if it’s true.

Otherwise, we set the background to blue.

Conclusion

To check if the time is between 7pm and 7am and do something with JavaScript, we can use the date’s getHours method to get the time.

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 *