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();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 niceCurrentDate = currentDate.toLocaleDateString();
var myDate = new Date("2019/01/21");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 niceMyDate = myDate.toLocaleDateString();
var monthsCurrentDate = currentDate.getMonth();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):
currentDate.setMonth(monthsCurrentDate - 1);
if (myDate < currentDate) {And there we have it!
Logger.log('Yes, my date is more than 1 month ago');
}
else {
Logger.log('No, my date is not more than 1 month ago');
}
Date - subtract month and compare.gs
No comments:
Post a Comment