简体   繁体   中英

Moment.js returns Invalid Date

The following code

const m = moment('08:45').format('HHmm')

returns

'Invalid date'

I have also tried .format('HH:mm')

Any ideas about what is going wrong here?

Just go ahead and pass in a format string as the second argument of the moment() function so that moment knows that you're passing in a time. So change your code to this:

const m = moment('08:45', 'HH:mm').format('HHmm');

and you'll be good to go :)

The input string doesn't match any of the expected date formats, so you need to add a second argument to tell moment how to parse the input.

String :

When creating a moment from a string, we first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of new Date(string) if a known format is not found.

String + Format :

If you know the format of an input string, you can use that to parse a moment.

moment("12-25-1995", "MM-DD-YYYY");

 const result = moment('08:45', 'HH:mm').format('HHmm'); console.log(result);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM