Home > Software engineering >  App Scripts stepping months and date formatting
App Scripts stepping months and date formatting

Time:03-19

I'm new to App Script, please be gentle!

I have a table with a start date and a number of months, I need to list each recurring month from the start date to the number of months.

I'm struggling with 2 issues:

  1. The first date placed in the array seems to be updating as I cycle the dates
  2. The formats are in UNIX and I can't get them to be useful despite an awful lot of reading!

Thank you so much for any help!

Input file (https://i.stack.imgur.com/2EJ65.png)

Output file(https://i.stack.imgur.com/0DH5R.png)

Console log (https://i.stack.imgur.com/NVqck.png)

var ss = SpreadsheetApp.getActiveSpreadsheet();

// Get Data sheet
var rawData = ss.getSheetByName('Sheet3');

// Get a date and set it as a date format
var start = new Date(rawData.getRange("B2").getValues());

console.log(start);

// Get Months
var months = rawData.getRange("C2").getValues();

// Define dates array
var dates = [];

// Add first date
const startDate = start
dates.push([startDate]);

//Add rest of dates dates in a loop
for (var run = 1;run < months;run  ) {
  //get the last pasted month name
  var lastMonth = start.getMonth();
  //push next month
  dates.push([start.setMonth(lastMonth 1)]);
}

// Get processedData sheet
var processedData = ss.getSheetByName('sheet2');

// Post the outputArray to the sheet in a single call
console.log(start);
console.log(startDate);
console.log(dates);
console.log(dates.length);
console.log(dates[0].length);

processedData.getRange(1,1,6,1).setValues(dates);
 
}

CodePudding user response:

Incrementing Dates by month and setting format

function lfunko() {
  const ss = SpreadsheetApp.getActive();
  let dt = new Date();
  let start = new Date(dt.getFullYear(),dt.getMonth(),dt.getDate());//need to change back to your value
  const months = 10;//need to change back to your value
  let dates = [];
  dates.push([start]);
  for (let run = 1; run < months; run  ) {
    dates.push([new Date(start.getFullYear(),start.getMonth()   run, start.getDate())])
  }
  ss.getSheetByName('Sheet0').getRange(1, 1, dates.length).setValues(dates).setNumberFormat("mm/dd/yyyy");//changed sheet name
  Logger.log(dates);
}
  • Related