0

Can anyone tell me why this code would produce two different dates?

let now = new Date();  // today's date (1/2/2021)
Logger.log(now);       // Sat Jan 02 09:42:47 GMT-08:00 2021
Logger.log(new Date(now.getTime()-(2*1000*60*60*24)));   // Thu Dec 31 09:42:47 GMT-08:00 2020
Logger.log(Utilities.formatDate(new Date(now.getTime()-(2*1000*60*60*24)), "GMT-8", "MM/d/YYYY"));  // 12/31/2021

Why would Utilities.formateDate() change the date from 12/31/2020 to 12/31/2021?

******** SOLUTION *********

Change the date format from "MM/d/YYYY" to "MM/d/yyyy".

James VB
  • 93
  • 7
  • 1
    what is `Utilities`? PS: ah, seems to be a google apps script specific tool. I've added that tag to clarify. – Christian Fritz Jan 02 '21 at 18:02
  • This might help: https://stackoverflow.com/questions/28956532/google-apps-script-date-format-issue-utilities-formatdate – Filipe Jan 02 '21 at 18:02
  • check also the answer of [this](https://stackoverflow.com/questions/51904670/google-script-formatdate-off-by-1-year-when-input-date-is-dec-30-or-31) one. – Marios Jan 02 '21 at 18:11
  • Yes, Utilities.formatDate() is a google apps script tool. Good catch & thanks for adding the tag. – James VB Jan 02 '21 at 19:14
  • ... also, changing the format from ```"MM/d/YYYY"``` to ```"MM/d/yyyy"``` solved the issue. Many thanks to all! – James VB Jan 02 '21 at 19:15

1 Answers1

0

It's just a simple formatting problem. Look here

This: Logger.log(Utilities.formatDate(new Date(now.getTime()-(2*1000*60*60*24)), "GMT-8", "MM/d/YYYY"));

Should be this:

Logger.log(Utilities.formatDate(new Date(now.getTime()-(2*1000*60*60*24)), "GMT-8", "MM/d/yyyy"));

In other words just make the capital Y's lower case y's and you're there.

Cooper
  • 59,616
  • 6
  • 23
  • 54