Is a Year a Leap Year? Gregorian Calendar & JavaScript

Earth doesn’t perfectly orbit the Sun every 365 days. Rather, it irritatingly must make its orbit in oh, I don’t know, roughly 365.242190 days each year.

Due to this inconsiderate behaviour, we must add a leap year into our common calendar known as the Gregorian Calendar.

Like, I presume, many of us, I thought a leap year occurred every four years.

Whether it was a matter of being taught a half-truth from my school teachers many decades ago in School (possible), or simply not paying attention to said teachers (much much more possible), I was wrong on this account.

So, when is a leap year?

According to the very impressively sounding Royal Museum Greenwich, a leaps year must meet the following conditions:

  1. Any year that is a century (e.g. 2000, 2100, 2400, 1900) must be divisible by 400. So 2000 and, 2400 are leap years but 2100 and, 1900 are not.
  2. Any other year must be divisible by 4.

Yeap. It’s that first one, I didn’t know about.

So with this in mind, how would we determine if a year is a leap year in JavaScript?

Enter the JavaScript Modulo Operator

To determine if something is divisible by a number we can use the JavaScript modulo operator (%) to determine the remainder. If the remainder is zero we know it is divisible by a number.

So 12%4 would return 0 because 12 divides perfectly into three lots of four. Whereas 7%3 would have one left over.

Got it? Cool.

The Video

https://youtu.be/-dZb30LpD5I

The Video Tutorial

Releases  17 Sep 2024

Hire me for our next Google Workspace project.

The Code

Let’s now create a function called isLeapYear() that takes a four-digit number for our target year.

Remember our leap years rules.

Create and Publish Google Workspace Add-ons with Apps Script Course 300px

We need to:

  1. Check if the year is divisible by 400 (year%400 == 0)
  2. Check if the year is divisible by 4 (year%4 == 0)
    If it is, then:
  3. Check if the year isn’t divisible by 100 (year%100 != 0).

Give it a run to see the results.

Why not just use the Date object?

I actually did this in a previous tutorial to get a list of days of the year a particular weekday (e.g. Monday, Tuesday, Wednesday…etc) falls. You can check it out here:

Get the Day of the Year in JavaScript

However, I would say that a purely numerical approach is always going to significantly beat a multi-step constructor approach.

🐐You can support me for free by using this Amazon affiliate link in your next tech purchase :Computers & Stuff! 🐐

Check out this benchmark example:

benchmark JavaScript find leap year numerical approach vs Date construtor approachBig difference.

 

~Yagi

Leave a Reply