formating iso 8601 to "MMM" and "hourPM/AM" using moment js

Viewed 110

I have a date format like:

"2021-01-16T03:00:000Z"

I want to get something like below out of it using momentJs:

Jan 16 - 3am

I have written this code but it gives me invalid date error (I know the .format() parameter is not my desired date but I'm stuck on getting a valid date out of it in the first step and I can't find which parameter should I pass for my desired format):

moment("2021-01-16T03:00:000Z").format("YYYY-MM-DD h:mm:ss a");

How can I get the desired format date with momentJs?

2 Answers

Can you try this :

const a = moment("2021-01-16T03:00:00Z")
let   b = a.format("MMM Do [-] h a")
// MMM Do [-] h a
console.log(b)

You had a one more 0 that he want : 2021-01-16T03:00:00[0]Z

You need to pass it the string as YYYY:MM:DDTHH:MM:SS:

const getDateFormatted = str => {
  const date = str.slice(0,19);
  return moment(date).format("MMM DD - h a");
}
console.log( getDateFormatted("2021-01-16T03:00:000Z") );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>

EDIT: Since OP's expected time is 3am, and moment("2021-01-16T03:00:00Z").format("MMM DD - h a") would give the time as 5am, it's ok to split here. Otherwise, the correct way would be to format the string to the right date without changing the timezone.

Related