Thursday, August 11, 2011

Servoy TIP: Leap Year Function

There may be times in your solution when you need to see if a certain year is a leap year. Here's the basic rules to determine if a date is a leap year or not:

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)
{
 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";
 }
}
However, there's a MUCH easier way to do the same thing:
function isLeap(yr) {
 return new Date(yr,1,29).getDate() == 29;
}
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.

You can also test if your calculation is working - by looking at this list of all leap years 1800-2400.

No comments:

Web Analytics