JavaScript check if time is between 9am and 6pm?

By Gulshan Saini
Published in JavaScript
July 02, 2020
1 min read

Suppose you want to show a message to the user on the website or run any NodeJS job only when the time is between two hours of a day.

To achieve this we can easily figure out if the current hour is between two hours or not using JavaScript Date() object and take the appropriate action.

Date class will return the hours in military time using method getHours() - 6 pm is represented as 18 in military time.

const now = new Date().getHours()

 *  check if value in now is between 9am and 6pm
 *  9am -> 9
 *  6pm -> 18
if (now >= 9 && now <= 18) {
  console.log('We are open')
} else {
  console.log('Sorry!! we are closed')


Sorry!! we are closed

You could even extend this to minutes by using getMinutes() method and further check if minutes are also in a specified range or not.


Previous Article
How to conditionally render a component in React?

Related Posts

How to check if a string contains a substring in JavaScript?
January 05, 2021
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer



Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.
© 2021, All Rights Reserved.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media