0
votes

All,

Consider the following JavaScript snippet, which takes a stringified date and creates a new Date object:

var str = '2016-02-01';
var d = new Date(str);
console.log(d);

Running the above returns, for example, Mon Feb 01 2016 00:00:00 GMT+0000 (GMT Standard Time).

However, running the equivalent code as a Google Apps Script function does not yield the same result:

function strToDateTest() {
   var str = '2016-02-01';
   var d = new Date(str);
   Logger.log(d);
}

In this case, the output is Thu Jan 01 01:00:00 GMT+01:00 1970.

I assume, given the differing log outputs, Google Apps Script is using its own implementation of Date and not the native JavaScript object.

Could someone shed some light on this, and advise how best to parse date values in Google Apps Script?

1
Allowing implementations to parse date strings is very well known to be inconsistent across implementations, as a consequence it is strongly recommended against. Far better to manually parse date strings, a library can help or a simple function if you only have one format to deal with.RobG
I think you mean built–in Date object (i.e. the one provided by the implementation), not native (which is no longer defined in the language specification). So if Google Apps Script provides a Date object, then that is the built–in (your "native") Date object.RobG

1 Answers

2
votes

Form me Google Apps Script is not running the last ECMAScript version (doc here). So for what I could read this is not implemented in this version. If you decorate your string with "THH:mm:ss.sssZ" it should work:

function strToDateTest() {
   var str = '2016-02-01';
   str +='T00:00:00.000Z';
   var d = new Date(str);
   Logger.log(d);
}