简体   繁体   中英

Format datetime to DD-MMM-YYY HH:mm:ss using moment.js

I have date in this format

2017-01-09T18:30:00.000Z

I am using moment.js and I am trying to convert it into DD-MMM-YYY HH:mm:ss --> 09-Jan-2017 18:30:00

I have tried this method

dateTime = moment("2017-01-09T18:30:00.000Z").format("DD-MMM-YYYY HH:mm:ss");

But I got output like this 9/1/2017 0:00 What I miss?

The reason you're getting 00:00 is because moment converts the date object to your timezone. In order to remove this and format the date without the timezone, use moment.utc() .

Update your fiddle to this:

var dateTime = moment.utc("2017-01-09T18:30:00.000Z").format("DD-MMM-YYYY HH:mm:ss"); document.getElementById('output').innerText = dateTime;

and it will work, outputting: 09-Jan-2017 18:30:00

Try using:

dateTime = moment("2017-01-09T18:30:00.000Z").format("DD-MMM-YYYY HH:mm:ss"); // note the extra Y in YYYY
console.log(dateTime);
// => 10-Jan-2017 05:30:00

For the most part it looks like what you are doing is right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM