Leap Year checking in Javascript

Hi all,

Here is I'm going to check the given year is leap or not...How to do....check it out..

I don't state that this code is perfect but it does work.

Just copy and paste the following function in to script tag inside the header tag so that it can be called from anywhere in this HTML document.


function isleap()
{
var yr=document.getElementById("year").value;
if ((parseInt(yr)%4) == 0)
{
if (parseInt(yr)%100 == 0)
{
if (parseInt(yr)%400 != 0)
{
alert("Not Leap");
return "false";
}
if (parseInt(yr)%400 == 0)
{
alert("Leap");
return "true";
}
}
if (parseInt(yr)%100 != 0)
{
alert("Leap");
return "true";
}
}
if ((parseInt(yr)%4) != 0)
{
alert("Not Leap");
return "false";
}
}


Basically this code gives the rules to check if a year is a leap year. If the year is no divisible by 4 then it is not a leap year. If the year is divisible by 100 but not by 400 then it is not a leap year. Otherwise the remaining options leave us with a leap year so I hard coded what to do. The Reason I have coded in what to do otherwise is to highlight the two different statements of verifying that something does match and verifying something does not match.

Just call this script function where you want...as follows,


onclick="isleap()"

that's it....

...S.VinothkumaR.

2 comments:

ijAcK said...
This comment has been removed by the author.
ijAcK said...

Here is the other one using if...else Construct in C#

using System;
class LeapYear
{
static void Main(string[] args;
{
int Year;
Console.WriteLine("Enter the year: ");
Year = Convert.ToInt32 (Console.ReadLine());
if ((Year % 4 == 0) && (Year % 100 != 0 || Year % 400 ==0))
{
Console.WriteLine("The Year you have entered is a Leap Year {0}", Year);
}
else
{
Console.WriteLine("The Year you have entered is not a Leap Year {0}", Year);
}
Console.ReaLine();
}
}