Pages

Tuesday, 14 January 2025

Check date in future and a Wednesday

The following Google Apps Script is designed to check that a date submitted via a Google Form is both in the future and falls on a Wednesday. This was developed as part of a newsletter submission process to help validate information and inform a user when they had not followed the instructions.

Google Form question asking for a date to be entered.

The Code

The trickiest part of this process is that the data coming from the Form is not recognised as a date specifically. So if you try to create a date object from it immediately you end up with an Americanised version that switches the day/month around. We therefore have to pull it apart:
var day = submissionDate.substring(0, 2);
var month = submissionDate.substring(3, 5);
var year = submissionDate.substring(6, 10);
Then piece it back together, remembering that JavaScript dates start at '0' for 'January' hence we subtract '1' from the month:
var newSubmissionDate = new Date(year, month - 1, day);
Next we want to look at extracting the day of the week from this date, so we can pop the days into an array and use 'getDay()' to return a value between 0 to 6 in order to work it out:
var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var dayOfTheWeek = newSubmissionDate.getDay();
var day = weekday[dayOfTheWeek];
With a little bit of formatting we can tidy up our submitted date into something like Wednesday 4 December 2024:
var niceSubmissionDate = Utilities.formatDate(newSubmissionDate, timeZone, 'EEEE d MMMMM yyyy');
Which takes us to our final step of comparing dates and checking the day of the week:
if ((newSubmissionDate < todaysDate) && (day != "Wednesday")) {

    console.log("Form date is in the past and not a Wednesday.");

} else if (newSubmissionDate < todaysDate) {

    console.log("Form date is in the past.");

} else if (day != "Wednesday") {

    console.log("Form date not a Wednesday.");

} else {

    console.log("All is good.");

};


Download

Check date in future and a Wednesday folder download (please use 'File' > 'Make a copy' for your own version of each item).

No comments:

Post a Comment