计算几个月和几天的年龄 [英] Calculating Age in Months and days
本文介绍了计算几个月和几天的年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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--;
}
document.write(age);
}
getAge("01/20/2011")
这显示我0年,但我想显示 10个月
和9个月,直到他的生日来临 10/20 / 2011
。
This shows me 0 years, but i would like to show 10 Months
and 9 Months until he his birthday comes 10/20/2011
.
推荐答案
通常情况下,您想知道一个人在特定日期的年龄,
或者两个日期之间的年,月和日。
It often happens that you want to know the age a person would be on a specific date, or the years, months and days between two dates.
如果您确实想要今天的年龄,请传递一个日期或日期字符串参数。
If you do want the age as-of today, pass a single date or datestring argument.
function getAge(fromdate, todate){
if(todate) todate= new Date(todate);
else todate= new Date();
var age= [], fromdate= new Date(fromdate),
y= [todate.getFullYear(), fromdate.getFullYear()],
ydiff= y[0]-y[1],
m= [todate.getMonth(), fromdate.getMonth()],
mdiff= m[0]-m[1],
d= [todate.getDate(), fromdate.getDate()],
ddiff= d[0]-d[1];
if(mdiff < 0 || (mdiff=== 0 && ddiff<0))--ydiff;
if(mdiff<0) mdiff+= 12;
if(ddiff<0){
fromdate.setMonth(m[1]+1, 0);
ddiff= fromdate.getDate()-d[1]+d[0];
--mdiff;
}
if(ydiff> 0) age.push(ydiff+ ' year'+(ydiff> 1? 's ':' '));
if(mdiff> 0) age.push(mdiff+ ' month'+(mdiff> 1? 's':''));
if(ddiff> 0) age.push(ddiff+ ' day'+(ddiff> 1? 's':''));
if(age.length>1) age.splice(age.length-1,0,' and ');
return age.join('');
}
getAge("1/25/1974")>> 37 years 8 months and 26 days
getAge("9/15/1984")>> 27 years 1 month and 5 days
getAge("12/20/1984","10,20,2011")>>26 years and 9 months
getAge(new Date(),"12/25/2011")+' till Christmas'>>
2 months and 5 days till Christmas
getAge("6/25/2011")>> 3 months and 25 days
这篇关于计算几个月和几天的年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文