从出生日期开始的 Javascript 年龄计数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5786186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Age count from Date of Birth
提问by Aditya P Bhatt
I'm passing my calendar selected date of birth
to following JS function for calculating Age:
我将我选择的日历传递date of birth
给以下用于计算年龄的 JS 函数:
var DOBmdy = date.split("-");
Bdate = new Date(DOBmdy[2],DOBmdy[0]-1,DOBmdy[1]);
BDateArr = (''+Bdate).split(' ');
//document.getElementById('DOW').value = BDateArr[0];
Cdate = new Date;
CDateArr = (''+Cdate).split(" ");
Age = CDateArr[3] - BDateArr[3];
Now, lets say, input age is: 2nd Aug 1983
and age count comes: 28
, while as August month has not been passed yet, i want to show the current age of 27
and not 28
现在,让我们说,输入年龄是:2nd Aug 1983
和年龄计数来了:28
,虽然八月还没有过去,我想显示当前的年龄27
而不是28
Any idea, how can i write that logic, to count age 27
perfectlywith my JS function.
任何想法,我如何编写该逻辑,以使用我的 JS 函数27
完美地计算年龄。
Thanks !
谢谢 !
回答by KooiInc
Let birth datebe august 2nd 1983, then the difference in milliseconds between now an that date is:
假设出生日期是 1983 年 8 月 2 日,那么现在与该日期之间的毫秒差为:
var diff = new Date - new Date('1983-08-02');
The difference in days is (1 second = 1000 ms, 1 hour = 60*60 seconds, 1 day = 24 * 1 hour)
天数的区别是(1秒=1000毫秒,1小时=60*60秒,1天=24*1小时)
var diffdays = diff / 1000 / (60 * 60 * 24);
The difference in years (so, the age) becomes (.25 to account for leapyears):
年份的差异(因此,年龄)变为(.25 以解释闰年):
var age = Math.floor(diffdays / 365.25);
Now try it with
现在试试
diff = new Date('2011-08-01') - new Date('1983-08-02'); //=> 27
diff = new Date('2011-08-02') - new Date('1983-08-02'); //=> 28
diff = new Date('2012-08-02') - new Date('1983-08-02'); //=> 29
So, your javascript could be rewritten as:
因此,您的 javascript 可以重写为:
var Bdate = new Date(date.split("-").reverse().join('-')),
age = Math.floor( ( (Cdate - Bdate) / 1000 / (60 * 60 * 24) ) / 365.25 );
[edit] Didn't pay enough attention. date.split('-')
gives the array [dd,mm,yyyy]
, so reversing it results in[yyyy,mm,dd]
. Now joining that again using '-', the result is the string 'yyyy-mm-dd'
, which is valid input for a new Date
.
[编辑] 没有引起足够的重视。date.split('-')
给出数组[dd,mm,yyyy]
,因此反转它会导致[yyyy,mm,dd]
. 现在再次使用“-”加入,结果是 string 'yyyy-mm-dd'
,它是 new 的有效输入Date
。
回答by Mark Kahn
(new Date() - new Date('08-02-1983')) / 1000 / 60 / 60 / 24 / 365.25
That will get you the difference in years, you will occasionallyrun into off-by-one-day issues using this.
这将使您获得数年的差异,您有时会遇到使用它的问题。
回答by Harry Joy
May be this works:
可能是这样的:
var today = new Date();
var d = document.getElementById("dob").value;
if (!/\d{4}\-\d{2}\-\d{2}/.test(d)) { // check valid format
return false;
}
d = d.split("-");
var byr = parseInt(d[0]);
var nowyear = today.getFullYear();
if (byr >= nowyear || byr < 1900) { // check valid year
return false;
}
var bmth = parseInt(d[1],10)-1;
if (bmth<0 || bmth>11) { // check valid month 0-11
return false;
}
var bdy = parseInt(d[2],10);
if (bdy<1 || bdy>31) { // check valid date according to month
return false;
}
var age = nowyear - byr;
var nowmonth = today.getMonth();
var nowday = today.getDate();
if (bmth > nowmonth) {age = age - 1} // next birthday not yet reached
else if (bmth == nowmonth && nowday < bdy) {age = age - 1}
alert('You are ' + age + ' years old');
回答by Stephen
I just had to write a function to do this and thought'd I'd share.
我只需要编写一个函数来做到这一点,并认为我会分享。
This is accurate from a human point of view! None of that crazy 365.2425 stuff.
从人的角度来看,这是准确的!没有那些疯狂的 365.2425 东西。
var ageCheck = function(yy, mm, dd) {
// validate input
yy = parseInt(yy,10);
mm = parseInt(mm,10);
dd = parseInt(dd,10);
if(isNaN(dd) || isNaN(mm) || isNaN(yy)) { return 0; }
if((dd < 1 || dd > 31) || (mm < 1 || mm > 12)) { return 0; }
// change human inputted month to javascript equivalent
mm = mm - 1;
// get today's date
var today = new Date();
var t_dd = today.getDate();
var t_mm = today.getMonth();
var t_yy = today.getFullYear();
// We are using last two digits, so make a guess of the century
if(yy == 0) { yy = "00"; }
else if(yy < 9) { yy = "0"+yy; }
yy = (today.getFullYear() < "20"+yy ? "19"+yy : "20"+yy);
// Work out the age!
var age = t_yy - yy - 1; // Starting point
if( mm < t_mm ) { age++;} // If it's past their birth month
if( mm == t_mm && dd <= t_dd) { age++; } // If it's past their birth day
return age;
}