Skip to content

Instantly share code, notes, and snippets.

@GarySwift
Forked from aaugustin/isValidDate.js
Created November 7, 2017 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GarySwift/b1ea8a6148bd7c1268bbd0a68bbddfe5 to your computer and use it in GitHub Desktop.
Save GarySwift/b1ea8a6148bd7c1268bbd0a68bbddfe5 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