【问题标题】:Calculating Age in Months and days以月和日计算年龄
【发布时间】:2011-10-20 09:20:56
【问题描述】:
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 Months 和 9 个月,直到他的生日到来 10/20/2011

【问题讨论】:

  • 您到底想得到什么。距离下一个生日还有几个月?还是人的年龄?请澄清。谢谢。

标签: javascript


【解决方案1】:

您经常想知道一个人在特定日期的年龄, 或两个日期之间的年、月和日。

如果您确实想要今天的年龄,请传递单个日期或日期字符串参数。

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

【讨论】:

  • 我认为应该有 if(mdiffjsfiddle.net/nxtwrld/nmp7F
  • 解决方案中存在错误。假设当前日期是 2016 年 2 月 16 日,而您将出生日期传递为 2015 年 2 月 17 日。然后上面的代码返回年龄为 27 天。
【解决方案2】:

有了这个,你可以有一个描述性的年龄文本:天、月和年:

function getAge(dateString) {

  var birthdate = new Date(dateString).getTime();
  var now = new Date().getTime();
  // now find the difference between now and the birthdate
  var n = (now - birthdate)/1000;

  if (n < 604800) { // less than a week
    var day_n = Math.floor(n/86400);
    return day_n + ' day' + (day_n > 1 ? 's' : '');
  } else if (n < 2629743) {  // less than a month
    var week_n = Math.floor(n/604800);
    return week_n + ' week' + (week_n > 1 ? 's' : '');
  } else if (n < 63113852) { // less than 24 months
    var month_n = Math.floor(n/2629743);
    return month_n + ' month' + (month_n > 1 ? 's' : '');
  } else { 
    var year_n = Math.floor(n/31556926);
    return year_n + ' year' + (year_n > 1 ? 's' : '');
  }
}


var age = getAge("01/20/2011");
alert(age);

【讨论】:

  • 这个答案帮了我很多兄弟:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
  • 2011-06-10
  • 2010-09-08
  • 2021-05-16
  • 2012-03-24
相关资源
最近更新 更多