year calculator for age code in javascript code example

Example 1: how to code a check age function in javascript

function Person(dob) {
  // [1] new Date(dateString)
  this.birthday = new Date(dob); // transform birthday in date-object
  
  this.calculateAge = function() {
    // diff = now (in ms) - birthday (in ms)
    // diff = age in ms
    const diff = Date.now() - this.birthday.getTime(); 
    
    // [2] new Date(value); -> value = ms since 1970
    // = do as if person was born in 1970
    // this works cause we are interested in age, not a year
    const ageDate = new Date(diff); 
    
    // check: 1989 = 1970 + 19
    console.log(ageDate.getUTCFullYear()); // 1989
    
    // age = year if person was born in 1970 (= 1989) - 1970 = 19
    return Math.abs(ageDate.getUTCFullYear() - 1970);
  };
}
var age =new Person('2000-1-1').calculateAge();
console.log(age); // 19

Example 2: Javascript code for Age calculator chatbot

var year;
var month;
var day;
var today = new Date();

console.log(Date());
Bot.send("Enter the year in which you were born");
var state = year;
async function respond(inputText) {
	if (state == year) {
		year = inputText;
		Bot.send("Enter the month in which you were born");
		state = month;
	}
	else if (state == month) {
		month = inputText;
		Bot.send("Enter the day");
		state = day;
	}
	else if (state == day) {
		day = inputText;
		if (month < today.getMonth()) {
			var age = today.getFullYear() - year;
			Bot.send("Your age is" + age);
		}
		else if (month > today.getMonth()) {
			var age = today.getFullYear() - year - 1;
			Bot.send("Your age is" + age);
		}
		else {
			if (day > today.getDay) {
				var age = today.getFullYear() - year - 1;
				Bot.send("Your age is " + age);
			}
			else {
				var age = today.getFullYear() - year;
				Bot.send("Your age is" + age);
				state = year;
			}
		}
	}

}