This returns a date Logger.log(sht.getRange(1,1).getValue())
How do I get the day of the month for that cell?
I tried
Logger.log(sht.getRange(1,1).getValue()).date()
and
Logger.log(date(sht.getRange(1,1).getValue()))
neither worked
This returns a date Logger.log(sht.getRange(1,1).getValue())
How do I get the day of the month for that cell?
I tried
Logger.log(sht.getRange(1,1).getValue()).date()
and
Logger.log(date(sht.getRange(1,1).getValue()))
neither worked
Using your sample spreadsheet as a guideline, and based on one of your comments:
I am trying to hide all the rows before the first day of a month and all the days after the end of a month. I have done this another way but I am trying to learn about how to correctly use this getDate function as part of making my whole sheet cleaner.
You can try to follow this:
hideRows()
and showRows()
function, respectively.You can refer to the following scripts for your reference:
The two functions for hiding and showing rows:
function hideRows(date, index) {
var ss = SpreadsheetApp.getActive();
var sht = ss.getActiveSheet();
// checks if the date is a weekend
if (date[index].getDay() == 0 || date[index].getDay() == 6) {
sht.hideRows(index + 2, 6); // you can change the 2nd integer depending on the number of rows populated on weekends
return index += 5;
}
// if the date is a weekday
else {
sht.hideRows(index + 2, 4); // you can change the 2nd integer depending on the number of rows populated on weekdays
return index += 3;
}
}
function unhideRows(date, index) {
var ss = SpreadsheetApp.getActive();
var sht = ss.getActiveSheet();
// checks if the date is a weekend
if (date[index].getDay() == 0 || date[index].getDay() == 6) {
sht.showRows(index + 2, 6); // you can change the 2nd integer depending on the number of rows populated on weekends
return index += 5;
}
// if the date is a weekday
else {
sht.showRows(index + 2, 4); // you can change the 2nd integer depending on the number of rows populated on weekdays
return index += 3;
}
}
The main function:
function myFunction() {
var ss = SpreadsheetApp.getActive();
var sht = ss.getActiveSheet();
var row = 2;
var date = sht.getRange(row, 1, sht.getLastRow() - (row - 1), 1).getValues().flat();
var today = new Date();
for (i = 0; i < date.length; i++) {
// a ternary operator that checks if
// a) the date on the spreadsheet is in the same month as today's date (to show the rows), or;
// b) hide all rows before the 1st date of the next month, or dates after the end of the previous month
date[i] != "" ? date[i].getMonth() == today.getMonth() || (date[i].getMonth() == today.getMonth() + 1 && date[i].getDate() == 1) ? i = unhideRows(date, i) : i = hideRows(date, i) : false;
}
}
For the ternary operator, its logic is similar to this if-else statement:
if (date[i] != "") {
if(date[i].getMonth() == today.getMonth() || (date[i].getMonth() == today.getMonth()+1 && date[i].getDate() == 1)){
unhideRows(date,i);
}
else{
hideRows(date,i);
}
}