Categories
JavaScript Answers

How to check the format of date with moment.js and JavaScript?

Spread the love

Sometimes, we want to check the format of date with moment.js and JavaScript.

In this article, we’ll look at how to check the format of date with moment.js and JavaScript.

How to check the format of date with moment.js and JavaScript?

To check the format of date with moment.js and JavaScript, we can use the moment.js’ isValid method.

For instance, we write:

const isValid = (d) => moment(d, 'DD-MMM-YYYY HH:mm a', true).isValid()

console.log(isValid('02-Mar-2022 01:01 AM'))
console.log(isValid('2022-02-03 01:01 AM'))

We define the isValid function that calls moment to try to parse the datetime string in 'DD-MMM-YYYY HH:mm a' format.

Then we call isValid to check if the datetime string is valid in the given format.

Therefore, datetimes that starts with a date, month and year separated by dashes and hours, minutes and AM or PM are valid.

As a result, the first console log is true and the 2nd one is false.

Conclusion

To check the format of date with moment.js and JavaScript, we can use the moment.js’ isValid method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to check the format of date with moment.js and JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *