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.
One reply on “How to check the format of date with moment.js and JavaScript?”
Great solution