How to determine if the year of a date is leap in MomentJS

Dates can be very problematic to handle in JavaScript when you don't use a powerful tool for them. In JavaScript, the most beloved library to handle dates is without a doubt Moment.js, a vanilla  JavaScript library for manipulating dates and time, without other dependencies provided. It's a powerful tool for parsing, validating and displaying dates.

In this short article, we'll show you how you can easily determine wheter a year is leap or not with JavaScript using the MomentJS library.

With a specific year

Create an instance of moment that receives as first argument an array with a single value, the year. From this instance, call the isLeapYear method that allows you to determine whether the year is leap or not:

moment([1752]).isLeapYear() // true
moment([2000]).isLeapYear() // true
moment([2001]).isLeapYear() // false
moment([2100]).isLeapYear() // false

With the year of an existent moment object

The idea with an object that already exists, is the same, for example given a variable that contain x date, determine wheter the year is leap or not with the same mentioned method (isLeapYear):

// the moment function contains the current datetime (e.g 07-04-2019 10:11)
let myDate = moment();

// 2019 is not a leap year, so it will print "no"
if(myDate.isLeapYear()){
    console.log("Yes");
}else{
    console.log("No");
}

Happy coding !

This could interest you

Become a more social person