Web Development

Checking leap year – the JS way

The algorithm for checking leap year is like the one below

1. if the year modulo 400 is 0 , its a leap year
2. else if the year modulo 100 is 0, then its not a leap year
3. else if the year modulo 4 is 0, its a leap year
4. else its not leap year

In plain JS, it will look something like the following one


function checkleapyear(year)
{
year = parseInt(year);

if(year%4 == 0)
{
if(year%100 != 0)
{
return true;
}
else
{
if(year%400 == 0)
return true;
else
return false;
}
}
return false;
}

I have seen this in numbers of web sites who are dealing with dates. But why bother when you can do it in the “Javascript way” – yes, take advantage of this fantastic language – heh heh. The following piece of code will do it for you


var dt = new Date(year+"/02/29");
if ("1"==dt.getMonth()) alert("leap year");
else alert("not leap year");

About the author

Written by .

If you found this post useful you may also want to check these out:

  1. Checking Form Field Integrity within PHP
  2. Disabling the Right-click Mouse Button
  3. A Class for Validating and Formatting Dates
  4. Using Arrays in JavaScripts
  5. Change Form Field Values, On The Fly, with JavaScript
  6. Ensuring Two Form Fields Have Identical Information