calculate age from date of birth in javascript code example
Example 1: javascript get age
function getAge(dateString)
{
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate()))
{
age--;
}
return age;
}
Example 2: javascript work out age from date of birth
var year_born = prompt("Please enter your date of birth:", "Type here");
var d = new Date();
var n = d.getFullYear();
function getAge(birthYear){
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
age = currentYear - birthYear;
return age;
}
calculatedAge = getAge(year_born);
alert("Hello, " + "you are " + calculatedAge + " years old!");
Example 3: 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)));
Example 4: how to code a check age function in javascript
function Person(dob) {
this.birthday = new Date(dob);
this.calculateAge = function() {
const diff = Date.now() - this.birthday.getTime();
const ageDate = new Date(diff);
console.log(ageDate.getUTCFullYear());
return Math.abs(ageDate.getUTCFullYear() - 1970);
};
}
var age =new Person('2000-1-1').calculateAge();
console.log(age);
Example 5: javascript calculate age
calculate Age using Javascript