如果给出格式为YYYYMMDD的出生日期,如何以年计算年龄?是否可以使用Date()函数?
我正在寻找一个比我现在使用的更好的解决方案:
Var dob = '19800810';
var年=数字(dob.)substr (0, 4));
var月=数字(dob.)Substr (4, 2)) - 1;
var day =数字(dob.)2) substr(6日);
var today = new Date();
var age = today.getFullYear() -年份;
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) {
年龄——;
}
警报(年龄);
不久前,我做了一个这样的函数:
function getAge(birthDate) {
var now = new Date();
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
// days since the birthdate
var days = Math.floor((now.getTime() - birthDate.getTime())/1000/60/60/24);
var age = 0;
// iterate the years
for (var y = birthDate.getFullYear(); y <= now.getFullYear(); y++){
var daysInYear = isLeap(y) ? 366 : 365;
if (days >= daysInYear){
days -= daysInYear;
age++;
// increment the age only if there are available enough days for the year.
}
}
return age;
}
它接受一个Date对象作为输入,所以你需要解析'YYYYMMDD'格式的日期字符串:
var birthDateStr = '19840831',
parts = birthDateStr.match(/(\d{4})(\d{2})(\d{2})/),
dateObj = new Date(parts[1], parts[2]-1, parts[3]); // months 0-based!
getAge(dateObj); // 26
我相信在这种情况下,有时可读性更重要。除非我们要验证1000个字段,否则这应该足够准确和快速:
函数is18orOlder(dateString) {
const dob = new Date(dateString);
const dobPlus18 =新的日期(dob.getFullYear() + 18, dob.getMonth(), dob.getDate());
返回dobPlus18 .valueOf() <= Date.now();
}
/ /测试:
console.log (is18orOlder (' 01/01/1910 '));/ /正确的
console.log (is18orOlder (' 01/01/2050 '));/ /错误
//当我在2020年10月2日发布这篇文章时,所以:
console.log (is18orOlder (' 10/08/2002 '));/ /正确的
console.log(is18orOlder('10/19/2002')) // false
我喜欢这种方法,而不是用一个常数来表示一年有多少毫秒,然后再弄乱闰年等等。让内置的Date来做这个工作。
更新,发布这个片段,因为有人可能会发现它有用。因为我在输入字段上强制一个掩码,有mm/dd/yyyy的格式,并且已经验证了日期是否有效,在我的情况下,这也适用于验证18+年:
function is18orOlder(dateString) {
const [month, date, year] = value.split('/');
return new Date(+year + 13, +month, +date).valueOf() <= Date.now();
}
这个问题已经超过10年了,没有人回答过提示,他们已经有了YYYYMMDD格式的出生日期?
如果你有一个YYYYMMDD格式的过去日期和当前日期,你可以像这样快速计算它们之间的年数:
var pastDate = '20101030';
var currentDate = '20210622';
var years = Math.floor( ( currentDate - pastDate ) * 0.0001 );
// 10 (10.9592)
你可以得到当前日期格式为YYYYMMDD,如下所示:
var now = new Date();
var currentDate = [
now.getFullYear(),
('0' + (now.getMonth() + 1) ).slice(-2),
('0' + now.getDate() ).slice(-2),
].join('');