本文介绍了给定出生日期的年龄,格式为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).

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

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.

基准:

Benchmarks: http://jsperf.com/birthday-calculation/15

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

09-22 04:41