Compare Dates in Google Apps Script: Easy & Quick

If you're working with dates in Google Apps Script, you may need to compare them at some point. Fortunately, this is a fairly simple task. Here's how to compare dates in Google Apps Script:

First, you'll need to convert your dates to a format that can be compared. The best format for this is Unix time, which is the number of seconds since January 1, 1970. You can convert a date to Unix time using the getTime() method.

Once you have your dates in Unix time format, you can compare them using standard comparison operators like <, >, and ==. For example, to check if one date is before another, you could write:


var date1 = new Date('2021-01-01');
var date2 = new Date('2021-02-01');
if (date1.getTime() < date2.getTime()) {
  Logger.log('date1 is before date2');
} else {
  Logger.log('date1 is after date2');
}

In this example, date1 is before date2, so the script will log "date1 is before date2".

You can also use the getTime() method to compare dates with the current date and time. For example, to check if a date is in the past, you could write:


var date = new Date('2021-01-01');
if (date.getTime() < new Date().getTime()) {
  Logger.log('date is in the past');
} else {
  Logger.log('date is in the future or is today');
}

In this example, date is in the past, so the script will log "date is in the past".

In summary, comparing dates in Google Apps Script is easy and quick. Just convert your dates to Unix time format and use standard comparison operators.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information