Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ?

like image 541
Sherlock Avatar asked Feb 13 '13 14:02

Sherlock


People also ask

How do I convert date to epoch date?

Convert from human-readable date to epoch long epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000; Timestamp in seconds, remove '/1000' for milliseconds. date +%s -d"Jan 1, 1980 00:00:01" Replace '-d' with '-ud' to input in GMT/UTC time.

How do I convert time to epoch?

Multiply the two dates' absolute difference by 86400 to get the Epoch Time in seconds – using the example dates above, is 319080600.

How do I convert timestamp to time in Unix?

To convert a date to a Unix timestamp:Create a Date object using the Date() constructor. Get a timestamp in milliseconds using the getTime() method. Convert the result to seconds by dividing by 1000 .


1 Answers

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.

like image 91
kanji Avatar answered Oct 02 '22 16:10

kanji