从生日开始年龄 [英] Get age from Birthdate

查看:125
本文介绍了从生日开始年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在JavaScript中计算年龄

在我的JS代码的某个方面有jquery date对象,即人的出生日期。我想根据他的出生日期来计算人的年龄。

In some point of my JS code I have jquery date object which is person's birth date. I want to calculate person's age based on his birth date.

任何人都可以提供有关如何实现这一点的示例代码。

Can anyone give example code on how to achieve this.

推荐答案

尝试此功能...

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

请参阅演示。

这篇关于从生日开始年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆