Chronological Age Calculator
Age on This Date:
// Populate days and years dynamically
function populateDays(selectElement) {
selectElement.innerHTML = '';
for (let i = 1; i <= 31; i++) {
selectElement.innerHTML += ``;
}
}
function populateYears(selectElement) {
const currentYear = new Date().getFullYear();
selectElement.innerHTML = '';
for (let i = currentYear; i >= currentYear - 100; i--) {
selectElement.innerHTML += ``;
}
}
populateDays(document.getElementById('birth-day'));
populateDays(document.getElementById('check-day'));
populateYears(document.getElementById('birth-year'));
populateYears(document.getElementById('check-year'));
document.getElementById('calculate').addEventListener('click', function() {
const birthMonth = parseInt(document.getElementById('birth-month').value);
const birthDay = parseInt(document.getElementById('birth-day').value);
const birthYear = parseInt(document.getElementById('birth-year').value);
const checkMonth = parseInt(document.getElementById('check-month').value);
const checkDay = parseInt(document.getElementById('check-day').value);
const checkYear = parseInt(document.getElementById('check-year').value);
if (isNaN(birthYear) || isNaN(checkYear) || isNaN(birthMonth) || isNaN(checkMonth) ||
isNaN(birthDay) || isNaN(checkDay)) {
document.getElementById('result').innerText = 'Please fill all fields correctly.';
return;
}
const birthDate = new Date(birthYear, birthMonth, birthDay);
const checkDate = new Date(checkYear, checkMonth, checkDay);
let years = checkDate.getFullYear() - birthDate.getFullYear();
let months = checkDate.getMonth() - birthDate.getMonth();
let days = checkDate.getDate() - birthDate.getDate();
if (days < 0) {
months--;
days += new Date(checkYear, checkMonth, 0).getDate(); // Get last day of previous month
}
if (months < 0) {
years--;
months += 12;
}
document.getElementById('result').innerText = `Your age on this date is ${years} years, ${months} months, and ${days} days.`;
});