Check if year is leap year in javascript [duplicate]
Asked Answered
M

7

101
 function leapYear(year){
    var result; 
    year = parseInt(document.getElementById("isYear").value);
    if (years/400){
      result = true
    }
    else if(years/100){
      result = false
    }
    else if(years/4){
      result= true
    }
    else{
      result= false
    }
    return result
 }

This is what I have so far (the entry is on a from thus stored in "isYear"), I basically followed this here, so using what I already have, how can I check if the entry is a leap year based on these conditions(note I may have done it wrong when implementing the pseudocode, please correct me if I have) Edit: Note this needs to use an integer not a date function

Mum answered 3/5, 2013 at 6:49 Comment(3)
check @ #8176021Bactericide
The thing is I need to deal with this as if I am working with only the year say 2014 as an integer not a date valueMum
A very detailed information on calculation is here - mathsisfun.com/leap-years.htmlHenrion
F
226
function leapYear(year)
{
  return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
Fulton answered 3/5, 2013 at 6:51 Comment(15)
Glad I could help. You can just use ´((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)´ where you need it if you don't want a function. I find functions helpful for having good human readable code though.Fulton
I already did as instructed, but thanks for the advice. I would love to use more functions, however I am not allowed to add any extra functions. Fairly restricting and making some other calculations annoying, but managing.Mum
FYI: This seems to be much more performant than isLeap (below) -- jsfiddle.net/atwright147/7dqzvzprBurrell
@atwright147, +1 for the performance check. It's interesting to note that nearly 96% of the time spent in "ily + defining function" goes to defining the function when compared to "ily".... (referring to your example jsfiddle.net/atwright147/7dqzvzpr)Moonmoonbeam
the fastest ever!!! can be reduced to that ... which speeds up a bit function isLeap (y) { return !((y % 4) || (!(y % 100) && y % 400)); }Azo
@Azo And I thought I had made the most concise one !(y%4)&&(!(y%400)||!!(y%100)); until I read your comment, but you did the inverse logic and saved two characters yet! Haha. Very well done.Russia
@Azo What about !(y&3||y&15&&!(y%25));? See https://mcmap.net/q/82760/-leap-year-check-using-bitwise-operators-amazing-speed/3167040 for details!Yun
sounds definitely interesting! I want to check it... thx!Azo
@Userthatisnotauser I ran a benchmark and !((y % 4) || (!(y % 100) && y % 400)) is a way faster, although less concise....anyway thx for sharing ;)Azo
@Azo Very interesting. How much faster was it?Yun
@Userthatisnotauser ~twice... curious!Azo
@Userthatisnotauser on ff, in chrome e.g. are similar, safari seems unstable in times...anyway ... jmvc.org/test_leapAzo
@Userthatisnotauser sometimes your shortest one is even faster (some mobile bro)Azo
minor nitpick but it is, for the most part, correct to use the strict (in)equality operator "===".Sully
I find my version more readable as it follows the common definition written in words: ((year % 4) == 0) && (((year % 100) != 0) || ((year % 400) == 0)); "Year is a leap year if it's divisible by 4 except years divisible by 100 - those are only leap years if they are divisible by 400".Vasiliu
M
74

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
Mycenaean answered 6/5, 2017 at 10:46 Comment(1)
I actually like this solution the best, because it doesn't require any underlying knowledge of the gregorian calendar.Parados
N
9

A faster solution is provided by Kevin P. Rice here:https://mcmap.net/q/35707/-how-to-find-leap-year-programmatically-in-c So here's the code:

function leapYear(year)
{
    return (year & 3) == 0 && ((year % 25) != 0 || (year & 15) == 0);
}
Netti answered 23/5, 2017 at 20:19 Comment(4)
This is more concise: !(y&3||y&15&&!(y%25))Yun
and less readable @YunAllcot
@Allcot Agreed, I must have commented that because of the comments on the accepted answer. Looking back, it's kind of silly: there's not any real benefits except when trying to make it hard to read...Yun
@Allcot or include a link to this post to make it more readable!Netti
M
1

If you're doing this in an Node.js app, you can use the leap-year package:

npm install --save leap-year

Then from your app, use the following code to verify whether the provided year or date object is a leap year:

var leapYear = require('leap-year');

leapYear(2014);
//=> false 

leapYear(2016);
//=> true 

Using a library like this has the advantage that you don't have to deal with the dirty details of getting all of the special cases right, since the library takes care of that.

Micelle answered 7/7, 2015 at 5:59 Comment(5)
But you're adding yet another dependency to your project for such a simple function. That's a no-no for me.Worrywart
Pulling in a package to check for three division remainders is frankly ridiculous.Clinton
Is it? If you take a look at the wrong answers in this question (people simply dividing by 4 and checking the remainder), using a library would probably be a wise decision for some people. The advantage of the library is that it includes test cases and has a better chance of working than people coming up with their own wrong implementation (see below for a couple of examples). Having said that, I understand that writing your own quick function (if you get it right) saves you from including one dependency - to each their own.Micelle
On the other hand, all of this might be overkill anyway. The next year where the simply year % 4 does not work is 2100, which most of the software built today is not going to see anyway. Add <irony> tags if you like...Micelle
right, and while a decent amount of software needs to handle 2000, 2000 also is a leap year. so unless your software needs to handle 1900 you're goodMartinet
N
-1

You can use the following code to check if it's a leap year:

ily = function(yr) {
    return (yr % 400) ? ((yr % 100) ? ((yr % 4) ? false : true) : false) : true;
}
Nannana answered 30/3, 2015 at 17:17 Comment(4)
Could you elaborate a bit?Rectrix
This seems like just a refactoring of the accepted answer. It's not any more compact or performing any different operations, so I'm not sure what value it would add.Rainy
this is pretty much molesting the ternary operatorFouts
This will be inefficient as it is always checking if a year is divisible by 400. You are getting 399 times False and one time TrueSickert
F
-11

You can try using JavaScript's Date Object

new Date(year,month).getFullYear()%4==0

This will return true or false.

Flasher answered 3/5, 2013 at 6:53 Comment(1)
It doesn't handle special cases (divisibility by 100 and 400).Switzerland
N
-15

My Code Is Very Easy To Understand

var year = 2015;
var LeapYear = year % 4;

if (LeapYear==0) {
    alert("This is Leap Year");
} else {
    alert("This is not leap year");
}
Neysa answered 22/8, 2016 at 1:21 Comment(1)
Your code is incorrect. 1900 was not a leap year, but your code will say that it was.Anthracnose

© 2022 - 2024 — McMap. All rights reserved.