I'm trying to return the nextMonth(), but currently both of the following functions I've made don't work.

//this one returns a string of "October1" instead of incrementing by 1 

function nextMonth()
  let month = Utilities.formatDate(new Date(), 'GMT+12:00', "MMMM");
  let year = Utilities.formatDate(new Date(), 'GMT+12:00', "yyyy");
  Logger.log(month + 1 + " " + year);

//this one returns the correct month number but no name of the month. 
I've thought about using an array of month values, and going through that array
using a for(;;) loop, but I'm actually not too good at loops at the moment. 

function nextMonth()
  let d = new Date().getMonth();
  let month = Utilities.formatDate(new Date(), 'GMT+12:00', d);
  let year = Utilities.formatDate(new Date(), 'GMT+12:00', "yyyy");
  Logger.log(month + " " + year);

Use Date.setMonth(), like this:

function nextMonth() {
  const dateNow = new Date();
  const dateNextMonth = new Date(dateNow);
  dateNextMonth.setMonth(dateNow.getMonth() + 1);
  const tz = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
  console.log(Utilities.formatDate(dateNow, tz, 'yyyy-MM-dd HH:mm');
  console.log(Utilities.formatDate(dateNextMonth, tz, 'yyyy-MM-dd HH:mm');
  console.log(Utilities.formatDate(dateNextMonth, tz, 'MMMM');

Note that the behavior of Date.setMonth() depends on the day of the month. Use a dayValue parameter of 1 if that is needed in your use case.

  • is new Date(dateNow); necessary? Wouldn't it be ok to leave it as dateNextMonth = new Date();?
    – Toko
    Oct 6 at 16:54
  • 1
    That's fine in this context, but the point is that you need two date objects pointing to the same moment. If you initialize both as new Date(), they will be close, but will not point to the exact same moment. That will matter if you later need to find the exact difference between the two or something similar. Further, you cannot copy a Date object with dateNextMonth = now because now is an object and therefore copied by refererence, which means that both variables would point to the same underlying Date object, rather than two different Date objects. Oct 6 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.