A year will be a leap year if it is divisible by 4 but not by 100. If a year is divisible by 4 and by 100, it is not a leap year unless it is also divisible by 400.
So, as always is the case when you use JavaScript - there are many different ways to get this done. I've seen some very long functions that use the "brute force" method to parse the date and check the year. Here's one example (modified for copy/paste use in Servoy 4+):
function isleap(yr)However, there's a MUCH easier way to do the same thing:
{
if ((parseInt(yr)%4) == 0)
{
if (parseInt(yr)%100 == 0)
{
if (parseInt(yr)%400 != 0)
{
application.output("Not Leap");
return "false";
}
if (parseInt(yr)%400 == 0)
{
application.output("Leap");
return "true";
}
}
if (parseInt(yr)%100 != 0)
{
application.output("Leap");
return "true";
}
}
if ((parseInt(yr)%4) != 0)
{
application.output("Not Leap");
return "false";
}
}
function isLeap(yr) {This function simply creates a new date with the year you pass in and February as the month (JavaScript months start at 0=January... yeah, I know - I HATE that as well!) and 29th as the day. JavaScript will auto-convert this to either Feb 29, yr - OR March 1, yr. So if the day that gets returned is the 29th - it's a leap year, if not, then it's not a leap year.
return new Date(yr,1,29).getDate() == 29;
}
You can also test if your calculation is working - by looking at this list of all leap years 1800-2400.
No comments:
Post a Comment