Check if year is leap year in javascript
The function checks if February has 29 days. If it does, then we have a leap year.
ES5
function isLeap(year) {
return new Date(year, 1, 29).getDate() === 29;
}
ES6
const isLeap = year => new Date(year, 1, 29).getDate() === 29;
Result
isLeap(1004) // true
isLeap(1001) // false
A faster solution is provided by Kevin P. Rice here:https://stackoverflow.com/a/11595914/5535820 So here's the code:
function leapYear(year)
{
return (year & 3) == 0 && ((year % 25) != 0 || (year & 15) == 0);
}
function leapYear(year)
{
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}