How to get correct Time with moment js

Viewed 142

I'm using moment.js for formatting date and time with format function, I'm getting correct output for date but whereas time is setting to 12:00 AM for all times by default. What ever time I give for below code it sets to 12:00 AM. Is there way to fix it?

  console.log(moment('2020-10-22 11:00:00', 'YYY-MM-DD').format('MMM DD - h:mm A'))
  //Received output: Oct 22 - 12:00 AM
  //Expected output: Oct 22 - 11:00 AM
2 Answers

You need to tell moment that it has to take into account the time other than the date.

console.log(moment('2020-10-22 11:30:00', 'YYY-MM-DD h:mm').format('MMM DD - h:mm A'))
//                                                   ^^^^
// In this case output is
// Oct 22 - 11:30 AM

Ciao, here working example:

console.log(moment('2020-10-22 11:00:00', 'YYY-MM-DD hh:mm').format('MMM DD - h:mm A'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

You forgot to put hour and minute format in moment() call

Related