## 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.
{"ft_lang_label":"__label__en","ft_lang_prob":0.86778337,"math_prob":0.87460613,"size":1443,"snap":"2019-26-2019-30","text_gpt3_token_len":409,"char_repetition_ratio":0.12300208,"word_repetition_ratio":0.06225681,"special_character_ratio":0.32501733,"punctuation_ratio":0.13680781,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9634095,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-07-21T18:53:51Z\",\"WARC-Record-ID\":\"<urn:uuid:ba31f931-5002-4c32-a47c-c7ef684902cb>\",\"Content-Length\":\"47629\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:10b47def-a0e8-4201-a524-a583ac1c46b8>\",\"WARC-Concurrent-To\":\"<urn:uuid:925f4821-76bd-404e-b517-631e30cecddc>\",\"WARC-IP-Address\":\"172.217.7.161\",\"WARC-Target-URI\":\"http://servoyuniversity.blogspot.com/2011/08/servoy-tip-leap-year-function.html\",\"WARC-Payload-Digest\":\"sha1:REQDLCGJH4WUYOGVEHOKTRUZCQCUWZAR\",\"WARC-Block-Digest\":\"sha1:JDSH26OOM3MLZUWU7PIWNASQ3CQTST2C\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-30/CC-MAIN-2019-30_segments_1563195527196.68_warc_CC-MAIN-20190721185027-20190721211027-00198.warc.gz\"}"}