Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...