Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert system date to ISO format using momentjs

I'm trying to convert system date to ISO format in below fashion using momentjs

2015-02-17T19:05:00.000Z 

I'm however unable to find the parameter that I need to use to get it in the format which I want. I tried below piece of code..

moment().format("YYYY-MM-DD HH:mm Z");

I get output as 2015-02-02 17:24+05:30.

How can I get it as 2015-02-02T17:24:00.000Z

like image 987
user1184100 Avatar asked Feb 02 '15 11:02

user1184100


1 Answers

This is pretty well covered in the docs. But, they're long, so here's the specifics:

For some reason, momentjs's definition of ISO 8601 differs from the ECMAScript one, so it isn't built in. The format is YYYY-MM-DDTHH:mm:ss.sssZ and it must be in UTC (the Z denotes this).

So, moment().utc() makes sure the timezone is correct.

Then format it:

moment().utc().format("YYYY-MM-DDTHH:mm:ss.SSS[Z]");
// 2015-02-02T21:38:04.092Z

The Z is escaped with square brackets. We can do this safely because we forced UTC.

The rest of the characters denote various time elements according to the format table.


You could also do what RobG said and use the native date object. In case you are starting with a moment:

moment().toDate().toISOString( )
// 2015-02-02T21:40:06.395Z
like image 171
DanielST Avatar answered Oct 26 '22 14:10

DanielST