substancev substancev - 1 year ago 54
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") {
} else {

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 Source

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") ) {
    } else {

Here is a fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download