I have a spreadsheet that I want to conditionally format according to dates. If a date is 7 days away, I want the cell to turn red, if a date is 14 days away, I want it to turn green, etc.
The first step to doing this, I figured, would be to create a simple conditional format script, where if a date is today, it would be highlighted. But my code doesn’t work 🙁
function formatting() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1'); // get the sheet
var columnF = sheet.getRange(2, 6, sheet.getLastRow()-1, 1); // get all the rows
var fValues = columnF.getValues(); // get the values
var today = Utilities.formatDate(new Date(), "GMT", "MM/dd/yyyy"); // get today's date
for (var i = 0; i < fValues.length; i++) { // repeat loop
if (fValues[i][0] == today) { // if the date in the cell is today's date...
sheet.getRange(i + 2, 6, 1, 1).setBackgroundColor('green'); // ...turn that cell green
}
}
}
What am I doing wrong?
Thanks!
You should not convert your date to a string, you can parse the date in days, month and years like in Srik’s answer, or you can also compare dates using their native values like below, it becomes easier to calculate other dates… I created a few variables to simplify the math :
day= the number of milliseconds in a daytoday= today’s date at 00:00 (in days)Test sheet available here