问题描述
我已经阅读过
(注意:这几天也是一个分数值,所以它会计算年龄到毫秒,如果你想整天,你可以在天的计算周围添加一个
Math.floor
c $ c>变量。)
I've read this question but there were many comments which some said it was accurate and some said it wasn't accurate.
Anyway I have this code which calc person's age in Javascript :
function calculateDiffYearByString(date)
{
var cur = new Date();
var diff = (cur.getTime() - new Date(date)) / (60 * 60 * 24 * 1000);
return diff / 365.242;
}
Now ,this part var diff = (cur.getTime() - new Date(date)) / (60 * 60 * 24 * 1000);
does consider all actual days (24 hr) from the start date till end date including leap year consideration.
It just count days by a 24 hr's groups.my question is about the / 365.242;
when I asked google , it said :
Which is why I devide it with 365.242.
but I think i'm wrong. becuase (IMHO) the .242
part is regarding the leap year. so I think I'm afraid the leap year is considered in the overall calculation twice ..
Am I wrong? does my calculation is 100% correct ?
The calculation is not correct, because of the assumption that a year is 365.242 days.
A year is by average 365.242 days, but there is no actual year that is 365.242 days. A year is either exactly 365 or 366 days (ignoring the small detail that there are some years that have leap seconds.)
To calculate the age as fractional years exactly, you would have to calculate the whole number of years up to the last birthday, and then calculate the fraction for the current year based on how many days the current year has.
You can use code like this to calculate the exact age in years:
function isLeapYear(year) {
var d = new Date(year, 1, 28);
d.setDate(d.getDate() + 1);
return d.getMonth() == 1;
}
function getAge(date) {
var d = new Date(date), now = new Date();
var years = now.getFullYear() - d.getFullYear();
d.setFullYear(d.getFullYear() + years);
if (d > now) {
years--;
d.setFullYear(d.getFullYear() - 1);
}
var days = (now.getTime() - d.getTime()) / (3600 * 24 * 1000);
return years + days / (isLeapYear(now.getFullYear()) ? 366 : 365);
}
var date = '1685-03-21';
alert(getAge(date) + ' years');
Demo: http://jsfiddle.net/Guffa/yMxck/
(Note: the days is also a fractional value, so it will calculate the age down to the exact millisecond. If you want whole days, you would add a Math.floor
around the calculation for the days
variable.)
这篇关于年龄(+闰年)计算在Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!