year calculator for age code in javascript code example
Example 1: 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 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;
}
}
}
}