Skip to content

Instantly share code, notes, and snippets.

@aaugustin
Created February 15, 2017 15:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aaugustin/a5d92add2fa53fc13f8e7b5020d9b321 to your computer and use it in GitHub Desktop.
Save aaugustin/a5d92add2fa53fc13f8e7b5020d9b321 to your computer and use it in GitHub Desktop.
isValidDate in JavaScript
export const DAYS_IN_MONTH = [null, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
function daysInMonth(year, month) {
// isValidDate checked that year and month are integers already.
// February of leap years. Assumes that the Gregorian calendar extends
// infinitely in the future and in the past.
if (month === 2 && (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0))) {
return 29
}
// Everything else.
return DAYS_IN_MONTH[month]
}
export function isValidDate(year, month, day) {
return (
// Check that year, month and day are integers. Deals with NaN.
year === Math.round(year) && month === Math.round(month) && day === Math.round(day) &&
// Any year is valid. Check that month and day are valid.
month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth(year, month)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment