Search code examples
javascriptdatetimeleap-year

How to determine whether a year is a leap year in JavaScript


I'm trying to determine whether a year is a leap year or not. I'm not sure where i'm missing something because this code is meant to determine that.

Thanks for your help.

let Year = (year) => {
    this.year = year;
};

Year.prototype.isLeap = () => {
    return (
        this.year % 400 === 0 ||
        (this.year % 4 === 0 && (this.year % 100 === 0))
    );
};

let year = new Year(2014);

year.isLeap();

Thanks I've figured it out.

Initially i did it will the kind of If statement you guys are pointing to here!, so I'm now refactoring to av a cleaner code.

My code was having issue on this line

(this.year % 4 === 0 && (this.year % 100 === 0))

the right syntax is

(this.year % 4 === 0 && !(this.year % 100 === 0))

Solution

  • You could just check the feburary 29th of the given year and see if its changes to march 1st.

    const date = new Date(this.year, 1, 29);
    return date.getMonth() === 1;
    

    If getMonth() returns 1, then its still feburary which means its leap year.