更新时间:2022-12-09 18:26:10
我会去阅读: strong>
function _calculateAge(birthday){// birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); //从epoch开始的毫秒数
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
免责声明:这也有精确的问题,所以这也不能完全信任。它可以关闭几个小时,几年或夏令时(取决于时区)。
相反,我建议使用一个库,如果精度非常重要。另外 @Naveens post
可能是最准确的,因为它不依赖于一天中的时间。
基准: http://jsperf.com/birthday-calculation/15
How can I calculate an age in years, given a birth date of format YYYYMMDD? Is it possible using the Date() class?
I am looking for a better solution than the one I am using now:
var dob='19800810';
var year=Number(dob.substr(0,4));
var month=Number(dob.substr(4,2))-1;
var day=Number(dob.substr(6,2));
var today=new Date();
var age=today.getFullYear()-year;
if(today.getMonth()<month || (today.getMonth()==month && today.getDate()<day)){age--;}
alert(age);
I would go for readability:
function _calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Disclaimer: This also has precision issues, so this cannot be completely trusted either. It can be off by a few hours, on some years, or during daylight saving (depending on timezone).
Instead I would recommend using a library for this, if precision is very important. Also @Naveens post
, is probably the most accurate, as it doesn't rely on the time of day.
Benchmarks: http://jsperf.com/birthday-calculation/15