Pooja Pooja - 4 months ago 65
Javascript Question

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?

Answer Source

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