Helping ordinary people create extraordinary websites!
 

Checking leap year – the JS way

by Hasin Hayder


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





Showcase Your Tutorials

Related Posts
» PHP-GTK2 is out!
» A comparison of search engine reach
» Social media’s just a fad? Think again.
» Valentine’s Day Fun with PHP and GD
» The 10/90 rule for web analytics
 


Leave a Reply



GET OUR NEWSLETTERS