如果给出格式为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)) {
年龄——;
}
警报(年龄);
从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>
我知道这是一个非常古老的线程,但我想把这个实现放在我写的寻找年龄,我相信这是更准确的。
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 ) ;
}
当然,你可以调整它以适应其他获取参数的格式。希望这有助于人们寻找更好的解决方案。
我只是不得不为自己写这个函数-接受的答案是相当好的,但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的因子。