function calcAge(birthdate) {
var nowDate = new Date()
if(!birthdate || birthdate == 'Invalid Date' || !(birthdate instanceof Date)) {
console.error('出生日期输入不合法')
return false
}
if(birthdate > nowDate) {
console.error('出生日期大于当前日期')
return false
}
var year = nowDate.getFullYear() - birthdate.getFullYear()
var month = nowDate.getMonth() - birthdate.getMonth()
var day = nowDate.getDate() - birthdate.getDate()
var hour = nowDate.getHours() - birthdate.getHours()
var minute = nowDate.getMinutes() - birthdate.getMinutes()
var second = nowDate.getSeconds() - birthdate.getSeconds()
second < 0 && minute-- && (second += 60)
minute < 0 && hour-- && (minute += 60)
hour < 0 && day-- && (hour += 24)
day < 0 && month-- && (day += new Date(birthdate.getFullYear(), birthdate.getMonth() + 1, 0).getDate())
month < 0 && year-- && (month += 12)
var age = `${year}年${month}月${day}日${hour}时${minute}分${second}秒`
return age
}
console.log(calcAge(new Date(1996, 0, 1))) // 24年10月12日15时14分52秒
ps:注意传入生日月份时要减1