substancev
substancev

Reputation: 19

How to call a function if current time is greater then and less then a specific time

I'm trying to call a function between specific hours.. Between 6:00:00 AM and 8:00:00 PM myFunction() should be executed.. otherwise otherFunction() should be executed.

if (new Date().getHours() > "6" && new Date().getHours() < "20") {
              myFunction();
} else {
              otherFunction();
}

The above sometimes works.. but i feel its not accurate... I was also using the moment.js and:

if (moment().format("h:mm:ss A") > "6:00:00 AM" && moment().format("h:mm:ss A") < "8:00:00 PM") {

I think I resolved it with:

    var now = moment();
    var amStart = moment('9:00 AM', 'h:mm A');
    var amFinish = moment('10:00 PM', 'h:mm A');
    if (now.isAfter(amStart) && now.isBefore(amFinish)) {
      console.log('Success Function');

    } else {
      console.log('Failure Function')
    }

Upvotes: 0

Views: 483

Answers (3)

substancev
substancev

Reputation: 19

This worked for me.

var now = moment();
var amStart = moment('9:00 AM', 'h:mm A');
var amFinish = moment('10:00 PM', 'h:mm A');
if (now.isAfter(amStart) && now.isBefore(amFinish)) {
  console.log('Success Function');

} else {
  console.log('Failure Function')
}

Upvotes: 0

Rafi Ud Daula Refat
Rafi Ud Daula Refat

Reputation: 2257

You can use isAfter() and isBefore() method of moment js. doc

   var date = new Date();
    if (moment(date).isAfter("6:00:00 AM") && moment(date).isBefore("8:00:00 PM") ) {
      successfuntion();
    } else {
      failerfunction();
    }

Here is a fiddle

https://jsfiddle.net/Refatrafi/yps8L631/4/

Upvotes: 0

Barmar
Barmar

Reputation: 780984

getHours() returns a number, not a string, so you should compare with numbers.

You need to use >=, not >, because when it's 6:10, getHours() will return 6, and 6 > 6 is not true.

var hour = new Date().getHours();
if (hour >= 6 && hour < 20) {
    myFunction();
} else {
    otherFunction();
}

Upvotes: 1

Related Questions