///Checking leap year – the JS way

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");

2008-02-25T13:38:42+00:00 February 25th, 2008|JavaScript|0 Comments

About the Author:

Leave A Comment