Leap Years Calculation with PHP, Java, Python and JavaScript
Determine leap years with different implementations in PHP, Java, Python and JavaScript.
The criteria to determine if a year is a leap year is simple:
- a leap year occurs when the year is divisible by 4 but not by 100
- except for years that are exactly divisible by 400
Examples:
- year 1904 war a leap year (divisible by 4)
- 1900 was not a leap year (divisible by 4 but also by 100)
- 2000 was a leap year as it is divisible by 400
PHP
For the calculation, we use the modulo operator to check whether a number is divisible: The modulo operator returns the remainder portion of a division. If one number is evenly divisible by another number, the remainder is 0.
function is_leap_year($year) {
if (($year % 400) == 0 || (($year % 4) == 0 && ($year % 100) != 0))
return true;
else
return false;
}
Java
In Java we can use the java.time API with the isLeap method:
import java.time.Year;
Year.of(2022).isLeap();
// or
Year.isLeap(2022);
The implementation of the isLeap method is slightly different than our PHP version:
public static boolean isLeap(long year) {
return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0);
}
Instead of the modulo division ($year % 400)
, the bitwise and is used to check if the year is divisible by 4.
Python
In Python we can rely on the calendar package:
import calendar
print(calendar.isleap(1904))
JavaScript
In JavaScript we can implement the method by hand similar to our PHP version. Or just check if the number of days in February is 29, which is the case for a leap year:
const isLeapYear = year => new Date(year, 1, 29).getDate() === 29;
We can also use a very good library date-fns which provides very useful methods for all kinds of date calculations:
import isLeapYear from 'date-fns/isLeapYear'
const result = isLeapYear(new Date(2012, 8, 1))
//=> true