16

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

1

1 Answer 1

42

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

3 Comments

Sweet mother of lord, finally I got the format for ISO for moment YYYY-MM-DDTHH:mm:ss.SSS[Z] :\
Thanks : works for moment-timezone because toISOString() not
@slicedtoad stuck with a similar issue, using your approach, works in converting the date to an ISO format but doesnt return the correct date - an example if the date that i am trying to convert is 05-04-2019 format dd-mm-yyyy it converts it to 2019-04-07T22:29:06.754Z which is not a correct date, what could be the issue here? this is the way i use it ----const stringinv = retreive.data.v_invoice_date, --let mmtinv = moment().utc(invoice).format("YYYY-MM-DDTHH:mm:ss.SSS[Z]")

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.