calculating days until expiration

111 views
Skip to first unread message

Melissa Varazlic

unread,
Oct 17, 2023, 5:00:35 PM10/17/23
to Google Apps Script Community
Here is what I have:
// Get the vendor's insurance expiration date.
var insuranceExpirationDate = worksheet.getRange("F" + i).getValue();

// Calculate the number of days until the vendor's insurance expires.
var daysUntilExpiration = insuranceExpirationDate - new Date();

// If the vendor's insurance expires within a month, send them an email.
if (daysUntilExpiration <= 30) {
  // Create the email message.

In one row the date is 12/30/2023. The logger shows that the script is calculating the Days until expiration: 6345129920. If I change the date to 10/2/2023 it shows: Days until expiration: -1349202341

I am not great at this so I know that I have something wrong but I can't find what it is.

Thanks!
Melissa

Ed Sambuco

unread,
Oct 17, 2023, 5:51:10 PM10/17/23
to google-apps-sc...@googlegroups.com
As a rule, all Javascript date calculations should be done with getTime() millisecond differences.
For current time, use (new.Date()).getTime()
For spreadsheet date, use sheet.getValue().getTime()

Then date difference = (current datetime - spreadsheet datetime)/(24*60*60*1000)  (divisor is number of milliseconds in a day)
Make sure the spreadsheet data is indeed formatted as a datetime.

You can use Math.floor to round the difference down to the next lower integer.


--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-script-community/0d1d88b8-6e41-4696-95cf-0490eab2cd98n%40googlegroups.com.

Ralph Messer

unread,
Oct 18, 2023, 1:35:51 AM10/18/23
to google-apps-sc...@googlegroups.com

The result is in milliseconds. try dividing by (1000 * 60 * 60 * 24)

Melissa Varazlic

unread,
Oct 20, 2023, 10:44:05 AM10/20/23
to Google Apps Script Community
Thank you both so much! 
Reply all
Reply to author
Forward
0 new messages