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
What Is the Most Efficient Way to Reverse an Array in JavaScript
How to Know When I'Ve Stopped Scrolling
How to Execute a Function on Pressing the Enter Key in an <Input> Field
How Does Setinterval and Settimeout Work
JavaScript "Variable Variables": How to Assign Variable Based on Another Variable
What's Wrong with Var X = New Array();
Jquery Attr('Checked','Checked') Works Only Once
Focus Next Element in Tab Index
Loading Backbone and Underscore Using Requirejs
Can't Set Innerhtml on Tbody in Ie
How to Pass Jsf Managed Bean Properties to a JavaScript Function
Removing Duplicate Objects with Underscore for JavaScript
How to Get Month and Date of JavaScript in 2 Digit Format
Event.Path Is Undefined Running in Firefox
Google Spreadsheet Script - How to Transpose/Rotate Multi-Dimensional Array
Adding Code to a JavaScript Function Programmatically