Created
February 15, 2017 15:12
-
-
Save aaugustin/a5d92add2fa53fc13f8e7b5020d9b321 to your computer and use it in GitHub Desktop.
isValidDate in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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