1function getAge(dateString)
2{
3 var today = new Date();
4 var birthDate = new Date(dateString);
5 var age = today.getFullYear() - birthDate.getFullYear();
6 var m = today.getMonth() - birthDate.getMonth();
7 if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate()))
8 {
9 age--;
10 }
11 return age;
12}
1const calAge = (date) => new Date(Date.now() - new Date(date).getTime()).getFullYear() - 1970;
2
1// To calculate age:
2var year_born = prompt("Please enter your date of birth:", "Type here");
3var d = new Date();
4var n = d.getFullYear();
5function getAge(birthYear){
6 var currentDate = new Date();
7 var currentYear = currentDate.getFullYear();
8 age = currentYear - birthYear;
9 return age;
10}
11calculatedAge = getAge(year_born);
12alert("Hello, " + "you are " + calculatedAge + " years old!");
1function Person(dob) {
2 // [1] new Date(dateString)
3 this.birthday = new Date(dob); // transform birthday in date-object
4
5 this.calculateAge = function() {
6 // diff = now (in ms) - birthday (in ms)
7 // diff = age in ms
8 const diff = Date.now() - this.birthday.getTime();
9
10 // [2] new Date(value); -> value = ms since 1970
11 // = do as if person was born in 1970
12 // this works cause we are interested in age, not a year
13 const ageDate = new Date(diff);
14
15 // check: 1989 = 1970 + 19
16 console.log(ageDate.getUTCFullYear()); // 1989
17
18 // age = year if person was born in 1970 (= 1989) - 1970 = 19
19 return Math.abs(ageDate.getUTCFullYear() - 1970);
20 };
21}
22var age =new Person('2000-1-1').calculateAge();
23console.log(age); // 19
24
1<!DOCTYPE html>
2<html>
3<head>
4 <meta charset="utf-8">
5 <title>JavaScript program to calculate age</title>
6</head>
7<body>
8
9</body>
10</html>
11
12