Check if date is valid in JavaScript
Question:
How to check if date is valid in JavaScript? Answer:
const dateStr = '2021-11-01';
if (Date.parse(dateStr)) {
console.log('valid date');
}
Description:
Maybe the simplest way to check if a date is valid in JavaScript is using the parse
method of the Date object. In case of a valid date, it returns the timestamp of the date and NaN otherwise. So it will not throw an error in case of invalid date inputs.
const dateStr = '2021-14-01';
if (Date.parse(true)) {
console.log('Valid date');
} else {
console.log('Invalid date');
}
Reference:
JavaScript Date parse reference
Share "How to check if date is valid in JavaScript?"
Related snippets:
- Convert milliseconds to minutes and seconds
- Check if date is valid in JavaScript
- Generate random date with JavaScript
- Generate random date in a range with JavaScript
- Check if date is today
- Get month name from Date in JavaScript
- Get the current date in JavaScript
- Get difference between 2 dates in JavaScript
- Get yesterday's date in JavaScript
- Get tomorrow's date in JavaScript
Tags:
check, date, valid, string, javascript Technical term:
Check if date is valid in JavaScript