Google Apps Script: parsing strings as Date object

2019-09-11 12:09发布

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条回答
老娘就宠你
2楼-- · 2019-09-11 12:29

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);
}
查看更多
登录 后发表回答