22

重複の可能性:
JavaScriptで年齢を計算する

私のJSコードのある時点で、人の誕生日であるjquerydateオブジェクトがあります。生年月日をもとに年齢を計算したい。

誰かがこれを達成する方法についてのサンプルコードを与えることができますか?

4

3 に答える 3

60

この機能を試してください...

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/

于 2012-04-04T09:09:00.967 に答える
36

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
于 2012-04-04T09:12:51.203 に答える
8
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;
}

JSFiddle

于 2012-04-04T09:19:54.050 に答える