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.