Leap year checker in javascript

I’m trying to put a leap year checker in my Age calculator. It worked for sometime and now it outputs "This is a leap year" every time I select a date. What am I doing wrong?? Thank you!

var year;

function ageCalculator() {
  var userinput = document.getElementById("DOB").value;
  var dob = new Date(userinput);

  if (userinput == null || userinput == '') {
    document.getElementById("message").innerHTML = "**Choose a date please!";
    return false;
  } else {
    //calculate month difference from current date in time
    var month_diff = Date.now() - dob.getTime();

    //convert the calculated difference in date format
    var age_dt = new Date(month_diff);

    //extract year from date
    var year = age_dt.getUTCFullYear();
    calYear();
    //now calculate the age of the user
    var age = Math.abs(year - 1970);

    //display the calculated age
    return document.getElementById("result").innerHTML =
      "Age is: " + age + " years. ";
  }
}

function calYear() {
  var yr = year;
  var yr = document.getElementsByName("year");
  if (yr % 400 == 0 || (yr % 100 != 0 && yr % 4 == 0)) {
    window.alert("This is not leap!");
  } else {
    window.alert("This is a leap!");
  }
}
<input type="text" id="DOB" />
<button type="button" onclick="ageCalculator()">Calculate</button>
<span id="message"></span><br/>
<span id="result"></span>

23 thoughts on “Leap year checker in javascript”

  1. const isLeap = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    
    const calcAge = (DOBString) => {
      const UTC_today = new Date();
      const UTC_DOB = new Date(DOBString);
      if (!UTC_DOB) return "Please, use a valid date";
      let age = UTC_today.getUTCFullYear() - UTC_DOB.getUTCFullYear();
      let m = UTC_today.getUTCMonth() - UTC_DOB.getUTCMonth();
      if (m < 0 || (m === 0 && UTC_today.getUTCDate() < UTC_DOB.getUTCDate())) age--;
      return {
        age: age,
        isLeap : isLeap(UTC_DOB.getUTCFullYear())
      }
    };
    
    const showAgeResult = () => {
      const ageObj = calcAge(EL_DOB.value);
      EL_result.textContent = `Age: ${ageObj.age}`;
      EL_leap.textContent = ageObj.isLeap ? "Born on a leap year! so cool" : "";
    };
    
    const EL_DOB = document.querySelector("#DOB");
    const EL_result = document.querySelector("#result");
    const EL_leap = document.querySelector("#leap");
    EL_DOB.addEventListener("input", showAgeResult);
    showAgeResult();
    <input id="DOB" type="date" value="2000-02-29"/>
    <span id="result"></span><br>
    <span id="leap"></span>

    Important:
    notice that if user DOB is "2000-02-29", only the "2001-03-01" will show 1y – such depends on

    Reply
  2. I suggest you look at this version

    Calculate age given the birth date in the format YYYYMMDD

    To fix YOUR code we need to pass the year to the function and not try to use a non-existing year field

    If there was such a field, you could access its value with document.querySelector("[name=year]").value since document.getElementsByName is a collection and the value would be document.getElementsByName("year")[0].value

    So what did I do?

    • passed the DOB year to the leap function
    • calculated the age from the year of the date difference

    I tested with 2000-02-29 and 2001-02-28

    NOTE the script ALSO works with 02/29/2016 but not with 29/02/2016 (European format)

    var year;
    
    function ageCalculator() {
      var userinput = document.getElementById("DOB").value;
      var dob = new Date(userinput);
    
      if (isNaN(dob)) {
        document.getElementById("message").innerHTML = "**Choose a date please!";
        return false;
      } else {
    
        //extract year from date
        var year = dob.getFullYear();
        console.log(year)
        calYear(year);
    
        //calculate difference from current date in milliseconds
        var date_diff = Date.now() - dob.getTime();
    
        //convert the calculated difference in date format
        var age_dt = new Date(date_diff);
    
       //now calculate the age of the user
        var age = Math.abs(1970 - age_dt.getFullYear());
    
        //display the calculated age
        return document.getElementById("result").innerHTML =
          "Age is: " + age + " years. ";
      }
    }
    
    function calYear(yr) {
      const isLeap = (yr % 400 == 0 || (yr % 100 != 0 && yr % 4 == 0)) 
      alert(isLeap ? "This is a leap!" : "This is not a leap!");
    }
    <input type="text" id="DOB" />
    <button type="button" onclick="ageCalculator()">Calculate</button>
    <span id="message"></span><br/>
    <span id="result"></span>
    Reply
  3. this is function to check if this year is leap year

    function isLeapYear(year){
     return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    }
    
    isLeapYear(2000) //true
    isLeapYear(2001) // false
    

    EDIT:
    so the problem is in document.getElementsByName("year")
    i think you should have a HTML named year which is have the year value

    <input type="number" name="year" />
    
    Reply
  4. Here’s another Method I can make sure it will works

    function ageCalculator() {
      var userinput = document.getElementById("DOB").value;
      var dob = new Date(userinput);
    
      if (userinput == null || userinput == '') {
        document.getElementById("message").innerHTML = "**Choose a date please!";
        return false;
      } else {
        //calculate month difference from current date in time
        var month_diff = Date.now() - dob.getTime();
    
        //convert the calculated difference in date format
        var age_dt = new Date(month_diff);
    
        //extract year from date
        var year = age_dt.getUTCFullYear();
        calYear(year);
        //now calculate the age of the user
        var age = Math.abs(year - 1970);
    
        //display the calculated age
        return document.getElementById("result").innerHTML =
          "Age is: " + age + " years. ";
      }
    }
    
    function calYear(yr) {
      if (yr % 400 == 0 || (yr % 100 != 0 && yr % 4 == 0)) {
        window.alert("This is not leap!");
      } else {
        window.alert("This is a leap!");
      }
    }
    
    Reply

Leave a Comment