Hey @lisamthorpe
You also need to check the month and day, not just the year, @yisrael-wix already gave you the answer, but I’m going to explain it for you and for others.
const date = $w('#datePicker').value; // Get the value from the date picker
function getAge(date) {
// A variable to see if the person age is above 18;
let legalAge = false;
// Variables for the age
let age = { year: 0, month: 0, day: 0 };
// Get today's date.
const today = new Date();
// Get the age of based on the birthday
age.year = today.getFullYear() - date.getFullYear(); // Get the year difference
age.month = today.getMonth() - date.getMonth(); // Get the month difference
age.day = today.getDate() - date.getDate(); // Get the day difference
if (age.month < 0) {
/* If the current month is past the birthday month, then the person
is one year younger, and we need decrease the year age.
*/
age.year--;
} else if (age.month === 0 && age.day < 0) {
/* If the current month is the same as the given month, and the current
day is before the person birthday day, and we need decrease the year age.
*/
age.year--;
}
// Check if the year difference is in the legal age (greater or equal to 18)
if (age.year >= 18) {
// Now check if the current month is after the birthday month or the same
if (age.month >= 0) {
// Now check if the current day is the same or after the birthday day
if (age.day >= 0) {
// The person is 18 years old or more.
legalAge = true;
}
}
}
/* prepare the data to return it - you don't need this part
This part will return the age like this (19 Years, 5 Months and 7 Days)
*/
let ageText = `${age.year} Years`;
if (age.month > 0) {
if (age.month === 1) {
ageText = `${ageText}, 1 Month`;
} else if (age.month > 1) {
ageText = `${ageText}, ${age.month} Months`;
}
}
if (age.day > 0) {
if (age.day === 1) {
ageText = `${ageText} and 1 Day`;
} else if (age.day > 1) {
ageText = `${ageText} and ${age.day} Days`;
}
}
// Return the final results.
return {
legalAge: legalAge,
age: {
numeric: age.year,
text: ageText
}
}
}
/* Calling the function getAge() with the date picker as a parameter
will return the following result - It'll differ by the date you select
*/
/*
Object {
legalAge: true,
age: {
numeric: 26,
text: "26 Years, 2 Months and 4 Days"
}
}
*/
Hope this helps~!
Ahmad