【问题标题】:Get age from Birthdate [duplicate]从出生日期获取年龄[重复]
【发布时间】:2012-04-17 23:31:03
【问题描述】:

可能重复:
Calculate age in JavaScript

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

谁能给出如何实现这一点的示例代码。

【问题讨论】:

  • 投反对票,因为它是easily searchable。想不出你是怎么得到这个赞成票的!

标签: javascript jquery date


【解决方案1】:

试试这个功能...

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/

【讨论】:

  • 非常酷!看到 if (age--;) 中只有一个命令,括号是可选的,但仍然相当不错。我还会将所有 var 声明用逗号组合成一个拆分,但总的来说,代码很棒,非常有用。谢谢老哥!
  • 试用了演示并给出了出生日期为 1998 年 6 月 1 日(今天是 2016 年 11 月 2 日)。这意味着现在18岁的人。但它显示错误消息,年龄应大于或等于 18。不准确因此投反对票。
  • 非常有用的代码
  • 如果年龄是从 axios json 数组中取出用于 v-for 的呢?
【解决方案2】:

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

【讨论】:

  • 我想你忘了在最后一行乘以 24
  • 呵呵doh。尽管如此,JsFiddle 是对的。谢谢
  • 可能最好除以 1000*60*60*24*365.25
  • 可能会删除最后一个 ')' 小括号。 -
  • 单线:Math.floor((new Date() - new Date("1990-01-01")) / 31557600000)
【解决方案3】:
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

【讨论】:

  • 比上面标记为答案的更准确。谢谢!!
  • 我认为“getDate()”会导致某些浏览器出现问题,我相信。
猜你喜欢
  • 2023-03-05
  • 2010-10-14
  • 2021-08-21
  • 2020-12-29
  • 1970-01-01
  • 2013-08-30
  • 1970-01-01
  • 2019-08-12
相关资源
最近更新 更多