Google Apps Script date format issue (Utilities.formatDate)

The Utilities.formatDate() utility formats a javascript String. However, when written out to the spreadsheet, the new row of data is interpreted by Google Sheets to determine data types and appropriate formatting, just as if you’d typed it in through the user interface.

Since you’ve got a recognizable date string, Google Sheets decides it’s a Date, stores it as such, and applies the default date format.

You’ve got two options for making the date in the spreadsheet meet your formatting needs.

  1. Force it to be interpreted as a String, even if it does look like a date.

    cell.setValue(Utilities.formatDate(new Date(), "GMT+10:00", "''yyyy-MM-dd"));
    //                                                           ^^ force string literal
    
  2. Set the date format for the cell. This will leave the value of the cell as a date, which is useful for calculations.

    Date formats follow the SimpleDateFormat specification.

    // Cell A1 contains a date
    var cell = SpreadsheetApp.getActiveSheet().getRange("A1");
    cell.setNumberFormat('yyyy-mm-dd');
    

Leave a Comment