KtheVeg
KtheVeg

Reputation: 133

How to detect if the time is between 2 set times (Google Apps Script)

So, I'm making a program, where when a specific function is called, it checks the current time, and executes an action depending on the time. Currently, inside my function, here is my code:

var d = new Date();
  var currentTime = d.toLocaleTimeString();
  var timeSplit = currentTime.split(':');
  var timeH = timeSplit[0];
  var timeM = timeSplit[1];
  var timePM = timeSplit[2].split(' ')[1]
  if (timeH >= 9 && timeM >= 30 && timePM == 'AM') {
    function1()
  } else if (timeH == 10 && timeM >= 25 && timeM < 30 && timePM == 'AM') {
    function2()
  } else if (timeH >= 10 && timeM <= 30 && timePM == 'AM') {
   function3()
  } else if (timeH >= 11 && timeM >= 40 && timePM == 'AM') {
    function4()
  }

You kinda get the point

It doesn't return any errors, but it also doesn't execute any functions either. How can I fix this?

Upvotes: 0

Views: 879

Answers (1)

Tanaike
Tanaike

Reputation: 201553

I think that in your script, timePM might be undefined. By this, no functions in the if statement are not run.

So how about this modification?

Pattern 1:

From:

var currentTime = d.toLocaleTimeString();

To:

var currentTime = d.toLocaleTimeString('en-US');

Pattern 2:

From:

var currentTime = d.toLocaleTimeString();
var timeSplit = currentTime.split(':');
var timeH = timeSplit[0];
var timeM = timeSplit[1];
var timePM = timeSplit[2].split(' ')[1]

To:

var h = d.getHours();
var timeH = h < 12 ? h : h - 12;
var timeM = d.getMinutes();
var timePM = d.getHours() < 12 ? 'AM' : 'PM';

Reference:

Upvotes: 2

Related Questions