Home > Software engineering >  getMonth() function deprecated. What replaces it? Can't run my script anymore
getMonth() function deprecated. What replaces it? Can't run my script anymore

Time:12-28

For the past year I've had a script that has worked great. Essentially if today's date matches the dates in my sheets it send a reminder email. To do this I have used the getMonth() function. But recently I started getting emails from google that the script failed, looking into it, getMonth() has been deprecated. What replaces it? I can't find any threads online about it.

Essentially what I've been doing is taking a date in sheets and converting it to simple dd/mm/yyyy format. Sheets and scripts date functions pull time, so this formula removes that from the equation.

There is probably a work around of pulling a date and removing the non essential information, but this formula worked for me. Is there a new 'getMonth()' function? Or do I have a rewrite how I do things entirely.

firstDay= sheet.getRange(rowCount,2).getValue();
firstDay = (firstDay.getMonth() 1)   "/"   firstDay.getDate()   "/"   firstDay.getFullYear();

This is the formula that no longer works.

CodePudding user response:

The Date.getMonth() method has not been deprecated.

To convert a Date object to a text string in Google Apps Script, observing the correct timezone offset, use Utilities.formatDate(), like this:

  const date = sheet.getRange(rowCount, 2).getValue();
  if (Object.prototype.toString.call(date) !== '[object Date]') {
    throw new Error(`The value '${date}' in row  ${rowCount} is not a date.`);
  }
  const timezone = sheet.getParent().getSpreadsheetTimeZone();
  const firstDay = Utilities.formatDate(value, timezone, 'yyyy-MM-dd');

Replace yyyy-MM-dd with your preferred date format.

CodePudding user response:

function getDateString() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  sh.getRange("A1").setValue(new Date());
  Logger.log(sh.getRange("A1").setNumberFormat("dd/MM/yyyy").getDisplayValue());
}

Execution log
10:30:45 AM Notice  Execution started
10:30:46 AM Info    27/12/2022
10:30:47 AM Notice  Execution completed
  • Related