Search code examples
javascriptvue.jsecmascript-6ecmascript-5

How to check user's age with Javascript based on 3 seperate inputs


I have 3 seperate inputs, one for day, month and year. Only the year is required to show on page load, the user only needs to fill in the year first.

Currently I am able to check if someone is over 16 or under 16 by simply checking the year.

checkAge() {
    let yearOfBirth = new Date().getFullYear() - this.form.dobYear;

    if (yearOfBirth > 16) {
      this.isSixteen = false;
      this.belowSixteen = false;
    }
}

When comparing the current year minus the user's input, if it equals to 16, then I have two select elements displaying the day and month, both of these will need to be filled in.

Here I need to compare the users input to see if the age is indeed 16, if they are a few months away from there 16th birthday for example then I want them to be seen as below 16, otherwise show them as 16 years of age.

I am using BootstrapVue and Vue.js also if it helps.


Solution

  • To check only the year:

    function calculateYearDiff(y){ // birthday year
       return (new Date()).getUTCFullYear() - y;
    }
    

    ^This will return difference in years between now and given year.

    To check full birthday date:

    function calculateAge(y,m,d){ // birthday year, month, day
       var birthday = new Date(y + '-' + m + '-' + d);
       var ageDifMs = Date.now() - birthday.getTime();
       var ageDate = new Date(ageDifMs);
       return Math.abs(ageDate.getUTCFullYear() - 1970);
    }
    

    ^This will return full years between given birthday and now.