Check if year is leap year in javascript
function leapYear(year)
{
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
How to determine whether a year is a leap year in JavaScript
You could just check the feburary 29th of the given year and see if its changes to march 1st.
const date = new Date(this.year, 1, 29);
return date.getMonth() === 1;
If getMonth()
returns 1, then its still feburary which means its leap year. Writing a JavaScript program to calculate a leap year
Your function is ok, except for a simple thing: you are missing the year parameter!
function isLeapYear(year) {
return year % 4 == 0 &&
(year % 100 !== 0 || year % 400 === 0);
}
But, with your extended syntax is ok too:function isLeapYear(year) {
if(year % 4 == 0)
{
if(year % 100 == 0)
{
if(year % 400 == 0)
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
else
{
return false;
}
}
isLeapYear(1900)
yields false
, as expected, 2000 true
, 1996 true
, 1997 false
.Seems legit to me.
Leap year Question in Javascript using nested if-else
If the year is divisible by 100, you need to check if the year is divisible by 400 too. But what you're missing is, if year is not divisible by 100 but divisible by 4, it is a leap year already. so you need to edit your code like following:
if (y % 4 === 0) {
if (y % 100 === 0) {
if (y % 400 === 0) {
alert(y + " is a leap year");
} else {
alert(y + " is not a leap year");
}
} else {
//if year is divisible by 4 but not 100, it is a leap year
alert(y + " is a leap year");
}
} else {
alert(y + " is not a leap year");
}
Related Topics
How to Get the Focused Element with Jquery
Ng-Model Does Not Update Controller Value
External Resource Not Being Loaded by Angularjs
Javascript: Uploading a File... Without a File
Does It Make Sense to Use Require.Js with Angular.Js
Angularjs "Controller As" or "$Scope"
Converting a Buffer into a Readablestream in Node.Js
Calling a JavaScript Function Recursively
Differencebetween JavaScript and Ecmascript
Single Quote Escape in JavaScript Function Parameters
Create File with Google Drive API V3 (Javascript)
Use of @ Symbol in Node Module Names
Professional Jquery Based Combobox Control
Rotate Object on Specific Axis Anywhere in Three.Js - Including Outside of Mesh
How to Remove Text (Without Removing Inner Elements) from a Parent Element Using Jquery