写一个js函数计算用户的年龄输入参数是出生日期
function calculateAge(birthDate) { var currentDate = new Date(); var birthYear = birthDate.getFullYear(); var currentYear = currentDate.getFullYear(); var age = currentYear - birthYear;
var birthMonth = birthDate.getMonth(); var currentMonth = currentDate.getMonth(); if (currentMonth < birthMonth) { age--; } else if (currentMonth == birthMonth) { var birthDay = birthDate.getDate(); var currentDay = currentDate.getDate(); if (currentDay < birthDay) { age--; } }
return age; }
// Example usage var inputDate = new Date("1990-06-15"); var age = calculateAge(inputDate); console.log(age); // Output: 3
原文地址: https://www.cveoy.top/t/topic/igvY 著作权归作者所有。请勿转载和采集!