0

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?

Pooja
  • 105
  • 4
  • 16
  • 1
    this `moment("2017-01-09T18:30:00.000Z").format("DD-MMM-YYYY HH:mm:ss");` gives `09-Jan-2017 23:30:00` which looks correct – Talha Awan Jul 17 '17 at 11:16
  • 2
    `YYY` is a bit odd (you get `172017`), other than that, [it looks fine](https://jsfiddle.net/b1z16gaf/). – James Thorpe Jul 17 '17 at 11:17
  • @James But my problem is I didn't get time. It is showing 00:00:00. I can manipulate date format but how would i get time? – Pooja Jul 17 '17 at 11:22
  • 1
    No idea - there must be something else going on that you're not showing us. How are you inspecting/outputting `dateTime` for instance, because what you say you're getting doesn't match the format specifier at all, even the date part. – James Thorpe Jul 17 '17 at 11:23
  • @James [it looks fine](https://jsfiddle.net/b1z16gaf/) this fiddle is also showing time like 00:00:00 – Pooja Jul 17 '17 at 11:36
  • @Pooja Uhh, the fiddle shows10-Jan-172017 05:30:00 – brennanenanen Jul 17 '17 at 11:38
  • 2
    It shows 20:30 for me, which is the GMT+2 time for the one you specified - 18:30. The reason (I think) it shows 00:00 for you is because (I assume) you live in India, and moment.js shows you the time with the timezone correction. – bamtheboozle Jul 17 '17 at 11:38
  • 1
    If that is all that's going on, and the rest of the output is in fact correct (I would have thought it would be `10-Jan-2017 00:00:00`), then your question is probably [a duplicate of this one](https://stackoverflow.com/questions/17855842/moment-js-utc-gives-wrong-date). – James Thorpe Jul 17 '17 at 11:40

2 Answers2

1

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

bamtheboozle
  • 5,847
  • 2
  • 17
  • 31
0

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.

brennanenanen
  • 409
  • 5
  • 10