Reputation: 321
Goal: My end goal is to add the number of rows that is equal to the number of days in a month. For that I believe we should be using this method: insertRows(rowIndex, numRows).
What I don't understand: However, I don't know how to calculate the number of days there are in a month of when the script was ran.
What I was able to find: There were other questions on Stack Overflow that regards a similar issue, however most of them has to do with calculating the number of days between two dates (example question: Google Apps Script: Number of days between two dates after subtracting full months). In my case, I'm not using two dates, rather wanting to calculate the number of days depending on what the current month is.
Hope you can help.
Upvotes: 1
Views: 2095
Reputation: 201418
I believe your goal as follows.
In this case, how about the following sample script?
function myFunction() {
const year = 2021; // Please set the year.
const month = 2; // Please set the month.
const days = (new Date(year, month, 0)).getDate();
console.log(days) // You can check the result.
// If you want to insert the rows from 1st row, you can use the following script.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
sheet.insertRows(1, days);
}
1
of sheet.insertRows(1, days);
.About your following replying,
Is there a way to do this dynamically without having to hardcode??
When you want to retrieve the number of days from this year and this month, how about the following script?
const date = new Date();
const days = (new Date(date.getFullYear(), date.getMonth() + 1, 0)).getDate();
console.log(days)
Upvotes: 2