从生日获取年龄

新手上路,请多包涵

可能重复:

在 JavaScript 中计算年龄

在我的 JS 代码的某些地方,我有 jquery 日期对象,它是人的出生日期。我想根据他的出生日期计算一个人的年龄。

任何人都可以提供有关如何实现此目标的示例代码。

原文由 Aram Gevorgyan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 830
2 个回答

试试这个功能…

 function calculate_age(birth_month,birth_day,birth_year)
{
    today_date = new Date();
    today_year = today_date.getFullYear();
    today_month = today_date.getMonth();
    today_day = today_date.getDate();
    age = today_year - birth_year;

    if ( today_month < (birth_month - 1))
    {
        age--;
    }
    if (((birth_month - 1) == today_month) && (today_day < birth_day))
    {
        age--;
    }
    return age;
}

或者

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--;
    }
    return age;
}

[ 见演示。 ][1] [1]:http://jsfiddle.net/mkginfo/LXEHp/7/

原文由 Ashwini Agarwal 发布,翻译遵循 CC BY-SA 4.0 许可协议

JsFiddle

您可以使用日期进行计算。

 var birthdate = new Date("1990/1/1");
var cur = new Date();
var diff = cur-birthdate; // This is the difference in milliseconds
var age = Math.floor(diff/31557600000); // Divide by 1000*60*60*24*365.25

原文由 Frank van Wijk 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题