Incorrect calculation date

31 views
Skip to first unread message

Václav Petrák

unread,
Sep 27, 2021, 5:11:03 AM9/27/21
to Google Apps Script Community
Hello,
I need to calculate the date by subtracting one day from the date I know. It only works well if it is not the first day of the year.

var timeZone = Session.getScriptTimeZone();
var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
var day= new Date(
2021, 0, 1);
var yesterday = new Date(day.getTime() - MILLIS_PER_DAY);


Logger.log(Utilities.formatDate(day, timeZone, "dd.MM.YYYY"));//return 01.01.2021
Logger.log(Utilities.formatDate(yesterday, timeZone, "dd.MM.YYYY"));//return 31.12.2021


The script then sets the last day of the year, but the year is incorrect!
Please, how can I solve this?
Thank you sorry for by bad English

Andrew Roberts

unread,
Sep 27, 2021, 5:33:45 AM9/27/21
to Google Apps Script Community
Weird! I can only guess you've found a bug in formatDate. I tried logging the values for different years and timezones and the yesterday date object is OK, it's just not formatting OK.

dimud...@gmail.com

unread,
Sep 27, 2021, 8:06:59 AM9/27/21
to Google Apps Script Community
NEVER use the upper-case "YYYY" formatter. ALWAYS use the lower-case "yyyy" formatter.
The following script will work as expected.

function testFormatDate() {
    var timeZone = Session.getScriptTimeZone();
    var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
    var day= new Date(
20210, 1);
    var yesterday = new Date(day.getTime() - MILLIS_PER_DAY);

    Logger.log(Utilities.formatDate(day, timeZone, "dd.MM.yyyy"));
    Logger.log(Utilities.formatDate(yesterday, timeZone, "dd.MM.yyyy"));
Reply all
Reply to author
Forward
0 new messages