2

In Google App Script consider the following date formatting code

function testDateFormatter(){
         // Sun Dec 31 2017 20:02:06
         var date = new Date(1514746926811)
         var dateString = Utilities.formatDate(date, "CET", "YYYY-MM-dd");    
         Logger.log("The date is : " + date + ", after formatting it is "  + dateString) 
    }

The result is:

//
// The date is : Sun Dec 31 2017 20:02:06 GMT+0100 (CET), after formatting it is 2018-12-31
//   

note 2018 instead of 2017 !!!!

Why GAS added the whole year to the date?

With other sample dates it works fine i.e.:

var date = new Date(1511377747255)
var dateString = Utilities.formatDate(date, "CET", "YYYY-MM-dd");    
Logger.log("The date is : " + date + ", after formatting it is "  + dateString) 
//
// Logger: The date is : Wed Nov 22 2017 20:09:07 GMT+0100 (CET), after formatting it is 2017-11-22
//
Rubén
  • 34,714
  • 9
  • 70
  • 166
user1749939
  • 221
  • 2
  • 6
  • 4
    Use `yyyy` to get calendar year, per [SimpleDateFormat](https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html). –  Dec 22 '17 at 22:10
  • it is so easy to miss between YYYY and yyyy - the type of error the will activate only few days a year. yyyy - the year of the actual date YYYY - the year of the #week (and for week 52 the year may still be the previous year even a data is in the new year.... – user1749939 Dec 03 '22 at 14:29

1 Answers1

-2

I don't see the problem:

function myFunction() {
  var dt=new Date(1514746926811);
  var dts=Utilities.formatDate(dt, Session.getScriptTimeZone(), "MM/dd/yyyy HH:mm:ss")//not YYYY
  Logger.log('dt=%s dts=%s',dt,dts);
}

Logger Output is:

[17-12-22 15:17:07:058 MST] dt=Sun Dec 31 12:02:06 GMT-07:00 2017 dts=12/31/2017 12:02:06

Cooper
  • 59,616
  • 6
  • 23
  • 54
  • The problem is clearly stated in the question; you have copied the example that the OP called "works fine" –  Dec 22 '17 at 22:10
  • Okay. I changed the date value. But the answer is still the same. I don't see the problem. – Cooper Dec 22 '17 at 22:18
  • 1
    Because your code is different from OP's code, of course. –  Dec 22 '17 at 22:24
  • It's a subtle difference and I didn't notice until I looked at it the second time. – Cooper Dec 22 '17 at 22:26