如果给出格式为YYYYMMDD的出生日期,如何以年计算年龄?是否可以使用Date()函数?
我正在寻找一个比我现在使用的更好的解决方案:
Var dob = '19800810';
var年=数字(dob.)substr (0, 4));
var月=数字(dob.)Substr (4, 2)) - 1;
var day =数字(dob.)2) substr(6日);
var today = new Date();
var age = today.getFullYear() -年份;
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) {
年龄——;
}
警报(年龄);
重要提示:这个答案并不能提供100%的准确答案,根据日期的不同,它会有10-20个小时的误差。
没有更好的解决方案(至少在这些答案中没有)。——纳文
我当然无法抗拒接受挑战的冲动,制作一个比目前公认的解决方案更快、更短的生日计算器。
我的解决方案的要点是,数学是快速的,所以不是使用分支和javascript提供的日期模型来计算解决方案,我们使用美妙的数学
答案是这样的,运行速度比naveen快65%,而且更短:
function calcAge(dateString) {
var birthday = +new Date(dateString);
return ~~((Date.now() - birthday) / (31557600000));
}
神奇的数字:31557600000等于24 * 3600 * 365.25 * 1000
也就是一年的长度,一年的长度是365天6小时,也就是0.25天。最后,我对结果进行了统计,得出了最终的年龄。
以下是基准测试:http://jsperf.com/birthday-calculation
要支持OP的数据格式,可以替换+new Date(dateString);
+新日期(d。Substr (0,4), d.substr(4,2)-1, d.substr(6,2));
如果你能想出一个更好的解决方案,请分享!:-)
不久前,我做了一个这样的函数:
function getAge(birthDate) {
var now = new Date();
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
// days since the birthdate
var days = Math.floor((now.getTime() - birthDate.getTime())/1000/60/60/24);
var age = 0;
// iterate the years
for (var y = birthDate.getFullYear(); y <= now.getFullYear(); y++){
var daysInYear = isLeap(y) ? 366 : 365;
if (days >= daysInYear){
days -= daysInYear;
age++;
// increment the age only if there are available enough days for the year.
}
}
return age;
}
它接受一个Date对象作为输入,所以你需要解析'YYYYMMDD'格式的日期字符串:
var birthDateStr = '19840831',
parts = birthDateStr.match(/(\d{4})(\d{2})(\d{2})/),
dateObj = new Date(parts[1], parts[2]-1, parts[3]); // months 0-based!
getAge(dateObj); // 26