Two functions of calculate current age on node js
// Function to calculate age
const calculateAge = async (date) => {
try {
const dateOfBirth = date;
// Split the date string into day, month, and year
const [day, month, year] = dateOfBirth.split('/');
// Construct a new Date object with the components
const dob = new Date(`${year}-${month}-${day}`);
// Validate the parsed date
if (isNaN(dob.getTime())) {
throw new Error('Invalid date format');
}
console.log(dob);
// Current date
const currentDate = new Date();
// Calculate the age
let age = currentDate.getFullYear() - dob.getFullYear();
// Check if the birthday has occurred this year
if (
currentDate.getMonth() < dob.getMonth() ||
(currentDate.getMonth() === dob.getMonth() &&
currentDate.getDate() < dob.getDate())
) {
age--;
}
return age;
} catch (error) {
console.log(error.message);
}
};
function calculateAgeSync(birthdate) {
// Split the date string into day, month, and year
const [day, month, year] = birthdate.split('/');
// Create a new Date object with the correct format (YYYY-MM-DD)
const formattedDate = `${year}-${month}-${day}`;
// Calculate age using the formatted date
const today = new Date();
const birthDate = new Date(formattedDate);
let age = today.getFullYear() - birthDate.getFullYear();
const monthDiff = today.getMonth() - birthDate.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}

0 Comments