0

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?

2
  • 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. Commented Aug 24, 2016 at 23:17
  • 1
    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. Commented Aug 24, 2016 at 23:23

1 Answer 1

3

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

According to the linked documentation, the built–in Date in Google Apps Script is based on ECMAScript ed 3, so you should not rely on it to parse any date string since that version of the standard does not specify any supported formats. Far better to manually parse strings with a simple function or library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.