从Birthdate获得年龄

Ara*_*yan 10 javascript jquery date

可能重复:
在JavaScript中计算年龄

在我的JS代码的某些方面,我有jquery日期对象,这是人的出生日期.我想根据他的出生日期来计算人的年龄.

任何人都可以举例说明如何实现这一目标.

Ash*_*wal 44

试试这个功能......

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;
}
Run Code Online (Sandbox Code Playgroud)

要么

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;
}
Run Code Online (Sandbox Code Playgroud)

见演示.

  • 很酷!就像在if(age--;)中只有一条命令一样,方括号是可选的,但仍然相当不错。我还将所有var声明与逗号合并为一个分割,但总体来说,很棒的代码非常有用。谢了哥们! (2认同)

Fra*_*ijk 25

的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
Run Code Online (Sandbox Code Playgroud)

  • 可能最好除以1000*60*60*24*365.25 (7认同)
  • 单行代码: ```Math.floor((new Date() - new Date("1990-01-01")) / 31557600000)``` (3认同)

fra*_*ity 6

function getAge(birthday) {
    var today = new Date();
    var thisYear = 0;
    if (today.getMonth() < birthday.getMonth()) {
        thisYear = 1;
    } else if ((today.getMonth() == birthday.getMonth()) && today.getDate() < birthday.getDate()) {
        thisYear = 1;
    }
    var age = today.getFullYear() - birthday.getFullYear() - thisYear;
    return age;
}
Run Code Online (Sandbox Code Playgroud)

的jsfiddle