如果给出格式为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 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>