# Age Calculation in JavaScript

You can easily find someone’s age by their date of birth. Calculating the age allows you to determine the user’s eligibility for certain features or content based on age restrictions. We can find the current date by using the Date() object in javascript. So, In this article, we will see about age calculation in javascript.

## 3 Types of Age Calculation

If you need to find only the year of age then follow the first method. If you want to find years, months, and days of age, then follow the second method. Finally follow the third method, if you want to find your age by a specific date

### 1. Find the year of age

In this method, we’ll get the user’s date of birth as input, if subtract it from the current date, we will get age. But we need to check whether the birthday has not yet come this year, for that we need to compare the current month and the month given in user input.

Code:

``````<html>
<title>Age Calculation with Year </title>
<body>
<center>
<b> Enter Date of Birth: <input type=number min="1930" placeholder="YYYY" id = DOB> </b> <br><br>
<button type="submit" onclick = "ageCalculator()"> Calculate age </button> <br>
<h3 id="result" align="center"></h3> </center>
</body>
<script>
function ageCalculator() {

var currentDate = new Date();
var userinput = document.getElementById("DOB").value;
var birthdateObj  = new Date(userinput);

let age = currentDate.getFullYear() - birthdateObj.getFullYear();

// Check if the birthday hasn't occurred yet this year
const hasBirthdayPassed = currentDate.getMonth() > birthdateObj.getMonth() ||
(currentDate.getMonth() === birthdateObj.getMonth() && currentDate.getDate() >= birthdateObj.getDate());

if (!hasBirthdayPassed) {
age--;
}

return document.getElementById("result").innerHTML = 'Age:' + age;
}

</script>
</html>``````

Output: Steps:

• Step 1: Create date input using <input> to get the date of birth from users, <button> tag to submit, and <h3> to display your age. You must set the `id name` to <input> and <h3> tags, only then we can detect the user input value and display age in h3. And set the ‘`onclick`‘ attribute of <button> to ‘`ageCalculator()`‘.
• Step 2: Create the javascript function ‘`ageCalculator()`‘ and find the current date using `Date()` object. Then find the value user input date using ” `document.getElementById().value`” and convert it into a date using the `Date()` object.
• Step 3: Subtract the current date year from the user input date and store it in a variable.
• Step 4: Check whether the birthday of this year has not yet arrived and if not then decrement the age by 1. If the birthday does not occur in the current year, it will be `1` a year more, we should be reduced it.
• Step 5: Finally, return the age to the <h3> tag by using “`document.getElementById().innerHTML`
READ ALSO  2 Easy Ways to Split Numbers in Javascript

### 2. Find the year, months & days of age

In this method, we are going to find not only the year of your age but also months and days. To find the year, month, and days of your age, you need to extract the year, month, and days of your date of birth separately and subtract it from the year, month, and days of your current date.

Code:

``````<html>
<title>Age Calculation with Year, months & days </title>
<body>
<center>
<b> Enter Date of Birth: <input type=date id = DOB> </b>
<button type="submit" onclick = "ageCalculator()"> Calculate age </button> <br>
<h3 id="result" align="center"></h3> </center>
</body>
<script>
function ageCalculator() {
var currentDate = new Date();
var userinput = document.getElementById("DOB").value;
var birthdate  = new Date(userinput);

const currentYear = currentDate.getFullYear();
const currentMonth = currentDate.getMonth();
const currentDay = currentDate.getDate();

const birthYear = birthdate.getFullYear();
const birthMonth = birthdate.getMonth();
const birthDay = birthdate.getDate();

let ageYears = currentYear - birthYear;
let ageMonths = currentMonth - birthMonth;
let ageDays = currentDay - birthDay;

if (ageMonths < 0 || (ageMonths === 0 && ageDays < 0)) {
ageYears--;
ageMonths += 12;
}

if (ageDays < 0) {
const daysInPreviousMonth = new Date(currentYear, currentMonth, 0).getDate();
ageDays += daysInPreviousMonth;
ageMonths--; }

return document.getElementById("result").innerHTML =  `Age: \${ageYears} years, \${ageMonths}months, \${ageDays} days`;
}
</script>
</html>``````

Output: Steps:

• Step 1: Get the value of the current date by using the `Date()` object and get the value of the user input date by using the”`document.getElementById().value`“.
• Step 2: Get the year, month, and day from the current date and user input date separately using “`getFullYear()`“, “`getMonth()`” and “getDate()” methods.
• Step 3: Subtract the current year from the user input year and store it in a variable. Then subtract the current Month from the user input Month and store it in a variable. And subtract the current Date from the user input Date and store it in a variable.
• Step 4: Check the events where the date of birth is not yet in the current year or month as in the above code and calculate the age accurately.
• Step 5: Finally, return the Years, Months, and Days in an HTML element.
READ ALSO  Overriding Function in JavaScript | Explained

### 3. Find age from birthday to a specific date

In this method, If you have both the birthdate and a specific reference date, you can calculate the age by finding the difference between the two dates.

Code:

``````<html>
<title>Age Calculation with Year, months & dates </title>
<body>
<center>
<b> Enter Date of Birth: </b> <br> <br>
<b>From :</b><input type=date id = fDOB>  </b>
<b>To :</b><input type=date id = tDOB>  </b>   <br> <br>
<button type="submit" onclick = "ageCalculator()"> Calculate age </button> <br>
<h3 style="color:32A80F" id="result" align="center"></h3> </center>
</body>
<script>
function ageCalculator() {
var fromInput = document.getElementById("fDOB").value;
var birthdateObj  = new Date(fromInput);

var toInput = document.getElementById("tDOB").value;
var referenceDateObj  = new Date(toInput);

let age = referenceDateObj.getFullYear() - birthdateObj.getFullYear();

// Check if the birthday hasn't occurred yet this year
const hasBirthdayPassed = referenceDateObj.getMonth() > birthdateObj.getMonth() ||
(referenceDateObj.getMonth() === birthdateObj.getMonth() && referenceDateObj.getDate() >= birthdateObj.getDate());

if (!hasBirthdayPassed) {
age--;
}

return document.getElementById("result").innerHTML =  'Age:' + age;
}
</script>
</html>``````

Output: Steps:

• Step 1: Create two input dates, one for from date and another one for to date. Create <button> for submitting and <h3> for displaying the result. And Set the `idnames` for both inputs and <h3> tags.
• Step 2: Get the value of two dates by using the”`document.getElementById().value`” and store it in the variable.
• Step 3: Check if a birthday hasn’t occurred yet this year by using the “if statement”. If the birthday is not yet in this year, decrement the age by `1`.
• Step 4: Return the age in the HTML element.