Monday 1 April 2019

Check if a date is more than a month ago

Recently during a consultation I was asked if it would be possible to check if the date submitted on a Google form was over a month ago, to which I responded "sure ...".

Admittedly this was a lot more difficulty than I thought it would (and should) be - I was bamboozled by online forums and posts suggesting to convert dates into numbers and perform other incoherent functions to achieve this. Eventually however I came across the single JavaScript function that I would need to achieve this feat ...... 'getMonth'.

In the below Google Apps Script code we start by getting the current date and presenting it in a nice format ('toLocaleDateString'). We need this date as it will be used to compare if our selected date is more than a month ago:
var currentDate = new Date();
var niceCurrentDate = currentDate.toLocaleDateString();
Next we select our chosen date which for the purpose of this post has been created manually, but in reality will come directly from a form input. This is the date we want to see if it is more than a month ago:
var myDate = new Date("2019/01/21");
var niceMyDate = myDate.toLocaleDateString();
Now we need to subtract 1 month (in this example) from our current date, after we have used 'getMonth' to determine its value first. An important note about this method is that the numbering starts at '0' - so January is 0, February is 1, and so on:
var monthsCurrentDate = currentDate.getMonth();
currentDate.setMonth(monthsCurrentDate - 1);
So now that we have adjusted the current date to a month ago we can perform a simple if statement to compare our chosen date and see if it is less than the adjusted current date (meaning it is more than a month ago):
if (myDate < currentDate) {
    Logger.log('Yes, my date is more than 1 month ago');
}
else {
    Logger.log('No, my date is not more than 1 month ago');
}
And there we have it!

Date - subtract month and compare.gs

No comments:

Post a Comment