This guide illustrates the complete procedure to compute “age” in JavaScript.
How to Calculate Age in JavaScript?
In JavaScript, the built-in “Date()” object and its associated methods i.e., “now()”, “getUTCFullYear()” allows the user to calculate the age according to the given date of birth. It requires the input date (DOB) and the current date to perform this task.
Example: Calculating Age Based on the User Input Date of Birth (DOB)
In this example, the age is calculated based on the user input DOB and the current Date.
HTML Code
First, an overview of the following HTML code:
In the above code snippet:
- The “<h2>” tag creates the first subheading.
- In the next step, the “<input>” tag adds an input field to choose the date having the “DOB” id.
- After that, create a button using the “onclick” event to allow the execution of a function named “ageCalculation()” at the button click.
- Lastly, the “<h3>” tag creates a second subheading aligned to “center” and an assigned id “result” to display the calculated age.
JavaScript Code
Now, have a look at the below-stated code:
function ageCalculation() {
var input = document.getElementById("DOB").value;
var dob = new Date(input);
var month_diff = Date.now() - dob.getTime();
var age_d = new Date(month_diff);
var year = age_d.getUTCFullYear();
var cal-age = Math.abs(year - 1970);
return document.getElementById("result").innerHTML ="Calulated Age is: " + age + "years.";
}
</script>
In the given code snippet:
- Define the function “ageCalculation()”.
- In its definition, the variable “input” utilizes the “document.getElementById()” method to fetch the input value using its id “DOB”.
- Next, the “dob” variable uses the “Date()” constructor having the user input date i.e., date of birth as its argument.
- After that, the “month-diff” variable computes the difference between the current date via the associated “now()” method and time in milliseconds elapsed since “January 1, 1970” retrieved via the “getTime()” method.
- The variable “age_d” converts the computed month difference into the date format.
- The variable “year” extracts the year from the date.
- The variable “cal–age” calculates the accurate age of a person by subtracting the retrieved calculation based on the 1970-year time from the fetched year.
- Lastly, the “document.getElementById()” method accesses the added heading using its id “result” to display the calculated age.
Output
As seen, the age is calculated according to the provided date of birth upon button click.
Conclusion
JavaScript provides the “Date” object and its associated predefined methods to perform the “Age Calculation”. It first utilizes the “Date()” constructor to take the user input date i.e., date of birth(DOB) from the calendar and then calculate the age according to the current date. This guide illustrated the age calculation operation in JavaScript.