Friday 9 August 2019

Get weekday name from a date

The following Google Apps Script code is designed to take a date, extract the day of the week from it (as a number initially, so Monday=1, Tuesday=2 ...) then use a 'switch' to determine the corresponding name of the day (eg Wednesday, Thursday ...).

The reason I was looking at this sort of code was for a project where a Google Form had to be completed in which the user selected a date in the future that should be a Wednesday. Without validation directly on the Form I tinkered around with the notion that Apps Script could first check the date before proceeding with handling the rest of the data.

The below example is just the code itself rather than also including the extra bits of a Google Form and extracting data directly from it. You could slot this function into you existing project and swap out the first part that simply gets the current date as a variable. When we use 'getDay' we can only return the day of the week as a number hence the need to then use the switch which looks through each case to match with the week-day number.

The result is a variable called day that now contains the name of the week-day which we could use an if statement to evaluate and proceed with the rest of our script.

Get weekday name from a date.gs

No comments:

Post a Comment