以 YYYYMMDD 格式计算给定出生日期的年龄 [英] Calculate age given the birth date in the format YYYYMMDD

查看:56
本文介绍了以 YYYYMMDD 格式计算给定出生日期的年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定格式为 YYYYMMDD 的出生日期,如何计算以年为单位的年龄?是否可以使用 Date() 函数?

How can I calculate an age in years, given a birth date of format YYYYMMDD? Is it possible using the Date() function?

我正在寻找比我现在使用的更好的解决方案:

I am looking for a better solution than the one I am using now:

var dob = '19800810';
var year = Number(dob.substr(0, 4));
var month = Number(dob.substr(4, 2)) - 1;
var day = Number(dob.substr(6, 2));
var today = new Date();
var age = today.getFullYear() - year;
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) {
  age--;
}
alert(age);

推荐答案

我会追求可读性:

function _calculateAge(birthday) { // birthday is a date
    var ageDifMs = Date.now() - birthday.getTime();
    var ageDate = new Date(ageDifMs); // miliseconds from epoch
    return Math.abs(ageDate.getUTCFullYear() - 1970);
}

免责声明:这也存在精度问题,因此也不能完全信任.它可能会关闭几个小时、某些年份或夏令时(取决于时区).

Disclaimer: This also has precision issues, so this cannot be completely trusted either. It can be off by a few hours, on some years, or during daylight saving (depending on timezone).

相反,如果精度非常重要,我会建议为此使用库.另外 @Naveens post 可能是最准确的,因为它不依赖于一天中的时间.

Instead I would recommend using a library for this, if precision is very important. Also @Naveens post, is probably the most accurate, as it doesn't rely on the time of day.

这篇关于以 YYYYMMDD 格式计算给定出生日期的年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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