google-apps-scriptformatdatetime

Google Script formatDate


I don't understand how does it work Utilities.formatDate(). I have script:

var A=new Date();
var B=Utilities.formatDate( A, SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone(), "YY.MM.dd HH:mm");

This has been working for months, but today (dec 31.) is problem... A=Tue Dec 31 2019 15:24:18 GMT+0100 (CET) B="2020.12.31 15:24" This is bug? How to fix a bug? I try yesterday date:

var A=new Date(new Date()-(1 * 24 * 60 * 60 * 1000));

but formatDate return: "20.12.30 15:24"


Solution

  • Try changing this "YY.MM.dd HH:mm" to "yy.MM.dd HH:mm"

    function tdate() {
      var A=new Date(new Date()-(1 * 24 * 60 * 60 * 1000));
      Logger.log(Utilities.formatDate(A,Session.getScriptTimeZone(),"yy.MM.dd HH:mm:ss"));
      //[19-12-31 13:44:34:975 MST] 19.12.30 13:44:34
      Logger.log(Utilities.formatDate(A,SpreadsheetApp.getActive().getSpreadsheetTimeZone(),"yy.MM.dd HH:mm:ss"));
      //[19-12-31 13:51:07:677 MST] 19.12.30 13:51:07
      Logger.log(Utilities.formatDate(A,Session.getScriptTimeZone(),"YY.MM.dd HH:mm:ss"));
      //[19-12-31 13:44:34:976 MST] 20.12.30 13:44:34
      Logger.log(Utilities.formatDate(A,SpreadsheetApp.getActive().getSpreadsheetTimeZone(),"YY.MM.dd HH:mm:ss"));
      //[19-12-31 13:51:07:678 MST] 20.12.30 13:51:07
    
    }
    

    Simple Date Format