2

I'm having trouble with something that should be very simple - just creating a Date() in Google Apps Script (javascript)

var thisdate = new Date('2017-02-12');
Logger.log(thisdate.toString());

This test results in 'Invalid Date'... I must be missing something really obvious!?

Thanks

Rubén
  • 34,714
  • 9
  • 70
  • 166
  • Possible duplicate of [Google Apps Script date format issue (Utilities.formatDate)](http://stackoverflow.com/questions/28956532/google-apps-script-date-format-issue-utilities-formatdate) – Deep 3015 Feb 18 '17 at 13:34

2 Answers2

1

Unfortunately, a date string in the format of '2017-02-12' won't work in Apps Script, even though it should be a valid JavaScript date string. You can replace the dashes with slashes, and it will work.

var d,string;

string = '2017-02-12';

if (string.indexOf("-") !== -1) {//A dash was found in the date string
  string = string.replace(/-/g,"/");//Replace dashes with slashes
  Logger.log(string)
  d = new Date(string);
} else {
  d = new Date(string);
}

Logger.log(d)
Alan Wells
  • 30,746
  • 15
  • 104
  • 152
1

You can pass the numbers, separated by comma, as arguments to the Date object constructor.

var d = new Date(2017, 2, 12); //year, month, date. 

The months start with 0, so 2 is actually March. In the example below, the output for month will be 3

  Logger.log(Utilities.formatDate(d, timezone, "dd-MM-yyyy"));
Anton Dementiev
  • 5,451
  • 4
  • 20
  • 32