Tom Wicks
Tom Wicks

Reputation: 1025

How to turn string to date using Moment

I'd like to turn

2021030213000 +0000

into this format

1:00 pm

I'm using Moment.js in the project and I've tried to do it like so

Moment("2021030213000 +0000").format('LT')

But it returns invalid date.

Any help would be hugely appreciated!

Upvotes: 0

Views: 56

Answers (2)

Alvin Abia
Alvin Abia

Reputation: 1266

So the problem here is that you are trying to invoke moment("dateStr") where your dateStr is not ISO-8601 compliant.

You can see the relevant API doc here: https://momentjs.com/docs/#/parsing/string/

You want to use moment's String+Format parser api in order to pass in a different format like the one you have above: https://momentjs.com/docs/#/parsing/string-format/

So for your case, it would look like:

moment("2021030213000 +0000", "YYYYMMDDHHmm +ZZ").format("LT")

Upvotes: 1

nourhero
nourhero

Reputation: 608

Hello you could use somethings like this:

var date = moment("2021030213000 +0000",  "YYYYMMDDhhmm").format('LT');
console.log(date);

Upvotes: 0

Related Questions