Converting a string timestamp to Date results in reset to UNIX epoch

Sherlock picture Sherlock · Feb 13, 2013 · Viewed 38.5k times · Source

I'm having some problems converting a string to a date object in google apps script.

My dates are in the following format, from a 3rd party API:

2013-01-17T17:34:50.507

I am attempting to convert this to a Date object:

return Date(stringDate);

And this is being returned:

Thu Jan 01 01:00:00 GMT+01:00 1970

Can someone tell me what i'm doing wrong, and how to resolve this issue ?

Answer

kanji picture kanji · May 13, 2017

With moment.js, it is as easy as this to parse any of ISO 8601 format.

var date = Moment.moment("2013-01-17T17:34:50.507").toDate();

You can use moment.js to parse your arbitrary date string as well.

To use moment.js in GAS, you just need to add it in the script editor. Open your script in GAS script editor and go to "Resources" then "Libraries...", then put this project key MHMchiX6c1bwSqGM1PZiW_PxhMjh3Sh48 and click "Add". Choose the version from the dropdown, then click "Save". Now, you are ready to use moment.js in GAS.

moment.js can be used to parse date string, create formatted date string, and many other date manipulation. Thanks to the author!

You can find the moment.js documentation here.