# how to calculate age from date of birth in javascript?

how to calculate age from date of birth in javascript – Calculate age from date of birth to current date. In our day to day programming we often come across business logic that depends on the age of a person.

## how to calculate age from date of birth in javascript

Contents

i am going to see how to calculate the age of a person using their birth date as input in JavaScript Example with demo.

### calculate age from date of birth in javascript

age calculator javascript

```function calculate_age(dob) {
var diff_ms = Date.now() - dob.getTime();
var age_dt = new Date(diff_ms);

return Math.abs(age_dt.getUTCFullYear() - 1970);
}

console.log(calculate_age(new Date(1982, 11, 4)));

console.log(calculate_age(new Date(1962, 1, 1)));
```

### Calculate age using JavaScript

Example 1: Predefined date input

```<script>
var dob = new Date("06/24/2001");

var month_diff = Date.now() - dob.getTime();

var age_dt = new Date(month_diff);

var year = age_dt.getUTCFullYear();

var age = Math.abs(year - 1970);

document.write("Age of the date entered: " + age + " years");
</script>
```

### Example 2: dynamic date input

index.html

```<html>
<script>
function ageCalculator() {
var memberIp = document.getElementById("DOB").value;
var dob = new Date(memberIp);
if(memberIp==null || memberIp=='') {
document.getElementById("message").innerHTML = "**Select a date please!";
return false;
} else {

var month_diff = Date.now() - dob.getTime();

var age_dt = new Date(month_diff);

var year = age_dt.getUTCFullYear();

var age = Math.abs(year - 1970);

return document.getElementById("result").innerHTML =
"Age is: " + age + " years. ";
}
}
</script>
<body>
<center>
<h2 style="color: 32A80F" align="center"> Calculate Age from Date of Birth <br> <br> </h2>

<b> Enter Date of Birth: <input type=date id = DOB> </b>
<span id = "message" style="color:red"> </span> <br><br>

<button type="submit" onclick = "ageCalculator()"> Calculate age </button> <br><br>
<h3 style="color:32A80F" id="result" align="center"></h3>
</center>
</body>
</html>
```

Also Read This 👉   javascript sort by date - How to sort an array by date value in JavaScript?

I hope you get an idea about how to calculate age from date of birth in javascript.
I would like to have feedback on my infinityknow.com blog.