Home > database >  How to construct time based if statements in Google Apps Script
How to construct time based if statements in Google Apps Script

Time:09-29

I am attempting to construct some simple logic for events happening in my spreadsheet before a certain time (2pm) each day. I want the function to tell me if the date entered represented in this case by the variable "tradeTime" is before or after 2pm CT. No matter what sample data I have provided the if statement always returns "Trade time is not less than 2pm" enter image description here

CodePudding user response:

You are currently comparing strings to each other which is not what you really want to do. Time or Date is easily converted to a numbers using the valueOf() function on a Date Object, see references for more information.

Therefore I propose the following:

function isEventBeforeDeadline(){
  const eventTime = new Date(2021,2,2,14).valueOf() 
  const deadline  = new Date(2021,2,2,14).valueOf()

  if( eventTime > deadline ) console.log("Too late")
  if( eventTime < deadline ) console.log("Made it")
  if( eventTime == deadline ) console.log("Perfect")
}

Please also see comments on your post.

  • Be more specific with where these dates are coming from, e.g. from a Sheet, API, or elsewhere. We assume you will not enter dates manually everyday.

  • Do not post images of code, post code of code. See here > Syntax Highlighting for Code

  • You are likely to need to build a Trigger which runs automatically. Then the code needs to be modified check for todays date, I assume. Here are the docs for that.

Reference

- Date Object

- Date.valueOf()

  • Related