Js计算年龄
计算年龄竟然还真的是个事
方法一, 找到今年的生日
function calculateAgeInYears (date) {
var now = new Date();
var year = now.getFullYear();
var age = year - date.getFullYear();
var birthday = new Date(year, date.getMonth(), date.getDate());
return now >= birthday? age: age - 1;
}
方法二, 虽然很简洁, 但是, 可能构造出特殊情况会导致计算错误. 主要是因为这个答案把闰年搭进去了.
const getAge = birthDate => ~~((new Date() - new Date(birthDate).getTime()) / 31557600000)
方法三,
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}