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"
Asked
Active
Viewed 509 times
-1

Sam
- 21
- 3
-
I think that `Utilities.formatDate()` returns the string value. [Ref](https://developers.google.com/apps-script/reference/utilities/utilities#formatDate(Date,String,String)) In your script, 2 string values are compared. I thought that this was the reason for your issue. So, in order to compare the time, I thought that this thread might be useful. https://stackoverflow.com/q/19004950 If this was not useful, I apologize. If this was useful, I would like to flag your question as the duplicated question for it. – Tanaike Sep 28 '21 at 00:49
-
https://stackoverflow.com/a/69347105/7215091 – Cooper Sep 28 '21 at 02:05
-
Add code and logs as text not as image. – Rubén Sep 28 '21 at 04:04
1 Answers
1
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

Neven Subotic
- 1,399
- 1
- 6
- 18