如果给出格式为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
为了测试生日是否已经过去,我定义了一个帮助函数Date.prototype。getDoY,它有效地返回一年中的天数。剩下的就不言自明了。
Date.prototype.getDoY = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.floor(((this - onejan) / 86400000) + 1);
};
function getAge(birthDate) {
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
var now = new Date(),
age = now.getFullYear() - birthDate.getFullYear(),
doyNow = now.getDoY(),
doyBirth = birthDate.getDoY();
// normalize day-of-year in leap years
if (isLeap(now.getFullYear()) && doyNow > 58 && doyBirth > 59)
doyNow--;
if (isLeap(birthDate.getFullYear()) && doyNow > 58 && doyBirth > 59)
doyBirth--;
if (doyNow <= doyBirth)
age--; // birthday not yet passed this year, so -1
return age;
};
var myBirth = new Date(2001, 6, 4);
console.log(getAge(myBirth));
这是我修改的尝试(用一个字符串传递给函数而不是一个日期对象):
function calculateAge(dobString) {
var dob = new Date(dobString);
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var birthdayThisYear = new Date(currentYear, dob.getMonth(), dob.getDate());
var age = currentYear - dob.getFullYear();
if(birthdayThisYear > currentDate) {
age--;
}
return age;
}
和用法:
console.log(calculateAge('1980-01-01'));
我只是不得不为自己写这个函数-接受的答案是相当好的,但IMO可以使用一些清理。这需要一个unix时间戳的dob,因为这是我的要求,但可以迅速适应使用字符串:
var getAge = function(dob) {
var measureDays = function(dateObj) {
return 31*dateObj.getMonth()+dateObj.getDate();
},
d = new Date(dob*1000),
now = new Date();
return now.getFullYear() - d.getFullYear() - (measureDays(now) < measureDays(d));
}
注意,我在measureDays函数中使用了31的固定值。所有计算所关心的是“年中的一天”是时间戳的单调递增度量。
如果使用javascript时间戳或字符串,显然需要删除1000的因子。
我知道这是一个非常古老的线程,但我想把这个实现放在我写的寻找年龄,我相信这是更准确的。
var getAge = function(year,month,date){
var today = new Date();
var dob = new Date();
dob.setFullYear(year);
dob.setMonth(month-1);
dob.setDate(date);
var timeDiff = today.valueOf() - dob.valueOf();
var milliInDay = 24*60*60*1000;
var noOfDays = timeDiff / milliInDay;
var daysInYear = 365.242;
return ( noOfDays / daysInYear ) ;
}
当然,你可以调整它以适应其他获取参数的格式。希望这有助于人们寻找更好的解决方案。
重要提示:这个答案并不能提供100%的准确答案,根据日期的不同,它会有10-20个小时的误差。
没有更好的解决方案(至少在这些答案中没有)。——纳文
我当然无法抗拒接受挑战的冲动,制作一个比目前公认的解决方案更快、更短的生日计算器。
我的解决方案的要点是,数学是快速的,所以不是使用分支和javascript提供的日期模型来计算解决方案,我们使用美妙的数学
答案是这样的,运行速度比naveen快65%,而且更短:
function calcAge(dateString) {
var birthday = +new Date(dateString);
return ~~((Date.now() - birthday) / (31557600000));
}
神奇的数字:31557600000等于24 * 3600 * 365.25 * 1000
也就是一年的长度,一年的长度是365天6小时,也就是0.25天。最后,我对结果进行了统计,得出了最终的年龄。
以下是基准测试:http://jsperf.com/birthday-calculation
要支持OP的数据格式,可以替换+new Date(dateString);
+新日期(d。Substr (0,4), d.substr(4,2)-1, d.substr(6,2));
如果你能想出一个更好的解决方案,请分享!:-)
使用momentjs "fromNow"方法,
这允许您使用格式化的日期,例如:03/15/1968
var dob = document.getElementByID(“dob”);
var age = moment(dob.value).fromNow(true).replace(“ years”, “”);
//fromNow(true) =>后缀“ago”不显示
//但是我们还是要去掉“years”;
作为原型版本
String.prototype.getAge = function() {
return moment(this.valueOf()).fromNow(true).replace(" years", "");
}
我有一个漂亮的答案,虽然它不是我的代码。不幸的是,我忘记了原来的帖子。
function calculateAge(y, m, d) {
var _birth = parseInt("" + y + affixZero(m) + affixZero(d));
var today = new Date();
var _today = parseInt("" + today.getFullYear() + affixZero(today.getMonth() + 1) + affixZero(today.getDate()));
return parseInt((_today - _birth) / 10000);
}
function affixZero(int) {
if (int < 10) int = "0" + int;
return "" + int;
}
var age = calculateAge(1980, 4, 22);
alert(age);
从naveen和原始OP的帖子中采用,我最终得到了一个可重用的方法存根,它接受字符串和/或JS Date对象。
我将其命名为gregorianAge(),因为这个计算准确地给出了我们如何使用公历表示年龄。即,如果月和日在出生年份的月和日之前,则不计算结束年。
/**
* Calculates human age in years given a birth day. Optionally ageAtDate
* can be provided to calculate age at a specific date
*
* @param string|Date Object birthDate
* @param string|Date Object ageAtDate optional
* @returns integer Age between birthday and a given date or today
*/
function gregorianAge(birthDate, ageAtDate) {
// convert birthDate to date object if already not
if (Object.prototype.toString.call(birthDate) !== '[object Date]')
birthDate = new Date(birthDate);
// use today's date if ageAtDate is not provided
if (typeof ageAtDate == "undefined")
ageAtDate = new Date();
// convert ageAtDate to date object if already not
else if (Object.prototype.toString.call(ageAtDate) !== '[object Date]')
ageAtDate = new Date(ageAtDate);
// if conversion to date object fails return null
if (ageAtDate == null || birthDate == null)
return null;
var _m = ageAtDate.getMonth() - birthDate.getMonth();
// answer: ageAt year minus birth year less one (1) if month and day of
// ageAt year is before month and day of birth year
return (ageAtDate.getFullYear()) - birthDate.getFullYear()
- ((_m < 0 || (_m === 0 && ageAtDate.getDate() < birthDate.getDate())) ? 1 : 0)
}
// Below is for the attached snippet
function showAge() {
$('#age').text(gregorianAge($('#dob').val()))
}
$(function() {
$(".datepicker").datepicker();
showAge();
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
DOB:
<input name="dob" value="12/31/1970" id="dob" class="datepicker" onChange="showAge()" /> AGE: <span id="age"><span>
使用javascript从出生日期获取年龄(年,月和日)
函数calcularEdad(年,月和日)
function calcularEdad(fecha) {
// Si la fecha es correcta, calculamos la edad
if (typeof fecha != "string" && fecha && esNumero(fecha.getTime())) {
fecha = formatDate(fecha, "yyyy-MM-dd");
}
var values = fecha.split("-");
var dia = values[2];
var mes = values[1];
var ano = values[0];
// cogemos los valores actuales
var fecha_hoy = new Date();
var ahora_ano = fecha_hoy.getYear();
var ahora_mes = fecha_hoy.getMonth() + 1;
var ahora_dia = fecha_hoy.getDate();
// realizamos el calculo
var edad = (ahora_ano + 1900) - ano;
if (ahora_mes < mes) {
edad--;
}
if ((mes == ahora_mes) && (ahora_dia < dia)) {
edad--;
}
if (edad > 1900) {
edad -= 1900;
}
// calculamos los meses
var meses = 0;
if (ahora_mes > mes && dia > ahora_dia)
meses = ahora_mes - mes - 1;
else if (ahora_mes > mes)
meses = ahora_mes - mes
if (ahora_mes < mes && dia < ahora_dia)
meses = 12 - (mes - ahora_mes);
else if (ahora_mes < mes)
meses = 12 - (mes - ahora_mes + 1);
if (ahora_mes == mes && dia > ahora_dia)
meses = 11;
// calculamos los dias
var dias = 0;
if (ahora_dia > dia)
dias = ahora_dia - dia;
if (ahora_dia < dia) {
ultimoDiaMes = new Date(ahora_ano, ahora_mes - 1, 0);
dias = ultimoDiaMes.getDate() - (dia - ahora_dia);
}
return edad + " años, " + meses + " meses y " + dias + " días";
}
函数esNumero
function esNumero(strNumber) {
if (strNumber == null) return false;
if (strNumber == undefined) return false;
if (typeof strNumber === "number" && !isNaN(strNumber)) return true;
if (strNumber == "") return false;
if (strNumber === "") return false;
var psInt, psFloat;
psInt = parseInt(strNumber);
psFloat = parseFloat(strNumber);
return !isNaN(strNumber) && !isNaN(psFloat);
}
我有点晚了,但我发现这是计算出生日期的最简单的方法。
希望这能有所帮助。
function init() {
writeYears("myage", 0, Age());
}
function Age() {
var birthday = new Date(1997, 02, 01), //Year, month-1 , day.
today = new Date(),
one_year = 1000 * 60 * 60 * 24 * 365;
return Math.floor((today.getTime() - birthday.getTime()) / one_year);
}
function writeYears(id, current, maximum) {
document.getElementById(id).innerHTML = current;
if (current < maximum) {
setTimeout(function() {
writeYears(id, ++current, maximum);
}, Math.sin(current / maximum) * 200);
}
}
init()
<span id="myage"></span>
我相信在这种情况下,有时可读性更重要。除非我们要验证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('');