Home > Enterprise >  Google Apps Script add month to a date until specific date is reached
Google Apps Script add month to a date until specific date is reached

Time:12-27

I have the following code using Google Apps Script, but when I log it out I get the following results. I want GAS to log the next month and stop once it gets to "lastDateofYear ". For whatever reason, the year doesn't change in my results, it just keeps repeating the current year. Please help.

var thisDate = "Mon Dec 20 00:00:00 GMT-06:00 2021";
var nextYear = Number(currentYear) 1;
var lastDateofYear = new Date("12-31-" nextYear);

  for(var i=thisDate; i <= lastDateofYear; ){  
    var currentiDate = new Date(i);     
    var month = currentiDate.getMonth() 1;
    i.setMonth((month) % 12);
    i.setDate(currentiDate.getDate());
    Logger.log(currentiDate);
  }

RESULTS:

Mon Dec 20 00:00:00 GMT-06:00 2021
Wed Jan 20 00:00:00 GMT-06:00 2021
Sat Feb 20 00:00:00 GMT-06:00 2021
Sat Mar 20 00:00:00 GMT-05:00 2021
Tue Apr 20 00:00:00 GMT-05:00 2021
Thu May 20 00:00:00 GMT-05:00 2021
Sun Jun 20 00:00:00 GMT-05:00 2021
Tue Jul 20 00:00:00 GMT-05:00 2021
Fri Aug 20 00:00:00 GMT-05:00 2021
Mon Sep 20 00:00:00 GMT-05:00 2021
Wed Oct 20 00:00:00 GMT-05:00 2021
Sat Nov 20 00:00:00 GMT-06:00 2021
Mon Dec 20 00:00:00 GMT-06:00 2021
Wed Jan 20 00:00:00 GMT-06:00 2021
Sat Feb 20 00:00:00 GMT-06:00 2021
Sat Mar 20 00:00:00 GMT-05:00 2021
Tue Apr 20 00:00:00 GMT-05:00 2021

CodePudding user response:

As I understand it, you want to print each month from the given date to the last month of the next year of the given date in the log.

You can do this in the following code:

let start = new Date("Mon Dec 20 00:00:00 GMT-06:00 2021");
let currentYear = new Date().getFullYear();
let nextYear = currentYear   1;
let end = new Date(nextYear, 11, 31);
while (start <= end) {
  // You can use Logger.log() here if you want. I use console.log() for demo purpose
  console.log(new Date(start).toDateString());
  start.setMonth(start.getMonth()   1);
}

If I got any part wrong, feel free to point it out to me in the comments.

  • Related