substancev substancev - 3 months ago 9
Javascript Question

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')
}

Answer

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/