Solana_Station
Solana_Station

Reputation: 321

How to generate a number of days in a month depending on the current month in Google Apps Script

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

Answers (1)

Tanaike
Tanaike

Reputation: 201418

I believe your goal as follows.

  • You want to retrieve the number of days in a month and want to insert the rows using the retrieved number.
  • You want to achieve this using Google Apps Script.

In this case, how about the following sample script?

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);
}
  • If you want to set the start row for inserting the rows, please modify 1 of sheet.insertRows(1, days);.

References:

Added:

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?

Sample script:

const date = new Date();
const days = (new Date(date.getFullYear(), date.getMonth() + 1, 0)).getDate();
console.log(days)

Upvotes: 2

Related Questions