如果出生日期格式为YYYYMMDD,我如何计算年龄?是否可以使用Date()
函数?
我正在寻找比我现在使用的解决方案更好的解决方案:
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);
答案 0 :(得分:462)
试试这个。
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
我认为代码中唯一看起来很粗糙的是substr
部分。
答案 1 :(得分:196)
我会考虑可读性:
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);
}
免责声明:这也有精确问题,因此也不能完全信任。它可以关闭几个小时,几年或夏令时(取决于时区)。
相反,如果精度非常重要,我会建议使用库。同样@Naveens post
,可能是最准确的,因为它不依赖于一天中的时间。
答案 2 :(得分:69)
重要提示:此答案不能提供100%准确的答案,根据日期约10-20小时。
没有更好的解决方案(无论如何都不在这些答案中)。 - naveen
我当然无法抗拒接受挑战并制作比目前接受的解决方案更快更短的生日计算器的冲动。 我的解决方案的要点是,数学是快速的,所以不是使用分支,而是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);
与+new Date(d.substr(0, 4), d.substr(4, 2)-1, d.substr(6, 2));
如果您能想出更好的解决方案,请分享! : - )
答案 3 :(得分:50)
使用momentjs:
/* The difference, in years, between NOW and 2012-05-07 */
moment().diff(moment('20120507', 'YYYYMMDD'), 'years')
答案 4 :(得分:12)
前段时间我用这个目的做了一个功能:
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
答案 5 :(得分:10)
清洁单线解决方案ES6写道:
const getAge = birthDate => Math.floor((new Date() - new Date(birthDate).getTime()) / 3.15576e+10)
// (today is 2018-06-13)
getAge('1994-06-14') // 23
getAge('1994-06-13') // 24
使用365.25天(因为闰年)
答案 6 :(得分:9)
这是我的解决方案,只需传递一个可解析的日期:
function getAge(birth) {
ageMS = Date.parse(Date()) - Date.parse(birth);
age = new Date();
age.setTime(ageMS);
ageYear = age.getFullYear() - 1970;
return ageYear;
// ageMonth = age.getMonth(); // Accurate calculation of the month part of the age
// ageDay = age.getDate(); // Approximate calculation of the day part of the age
}
答案 7 :(得分:5)
为了测试生日是否已经过去,我定义了一个辅助函数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));
答案 8 :(得分:5)
替代解决方案,因为为什么不:
function calculateAgeInYears (date) {
var now = new Date();
var current_year = now.getFullYear();
var year_diff = current_year - date.getFullYear();
var birthday_this_year = new Date(current_year, date.getMonth(), date.getDate());
var has_had_birthday_this_year = (now >= birthday_this_year);
return has_had_birthday_this_year
? year_diff
: year_diff - 1;
}
答案 9 :(得分:4)
function getAge(dateString) {
var dates = dateString.split("-");
var d = new Date();
var userday = dates[0];
var usermonth = dates[1];
var useryear = dates[2];
var curday = d.getDate();
var curmonth = d.getMonth()+1;
var curyear = d.getFullYear();
var age = curyear - useryear;
if((curmonth < usermonth) || ( (curmonth == usermonth) && curday < userday )){
age--;
}
return age;
}
要获得欧洲日期进入的年龄:
getAge('16-03-1989')
答案 10 :(得分:4)
我只需要为自己编写这个功能 - 接受的答案相当不错,但IMO可以使用一些清理工作。这需要一个unb时间戳为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。
答案 11 :(得分:4)
我认为可能就是这样:
function age(dateString){
let birth = new Date(dateString);
let now = new Date();
let beforeBirth = ((() => {birth.setDate(now.getDate());birth.setMonth(now.getMonth()); return birth.getTime()})() < birth.getTime()) ? 0 : 1;
return now.getFullYear() - birth.getFullYear() - beforeBirth;
}
age('09/20/1981');
//35
还可以使用时间戳
age(403501000000)
//34
答案 12 :(得分:4)
function age()
{
var birthdate = $j('#birthDate').val(); // in "mm/dd/yyyy" format
var senddate = $j('#expireDate').val(); // in "mm/dd/yyyy" format
var x = birthdate.split("/");
var y = senddate.split("/");
var bdays = x[1];
var bmonths = x[0];
var byear = x[2];
//alert(bdays);
var sdays = y[1];
var smonths = y[0];
var syear = y[2];
//alert(sdays);
if(sdays < bdays)
{
sdays = parseInt(sdays) + 30;
smonths = parseInt(smonths) - 1;
//alert(sdays);
var fdays = sdays - bdays;
//alert(fdays);
}
else{
var fdays = sdays - bdays;
}
if(smonths < bmonths)
{
smonths = parseInt(smonths) + 12;
syear = syear - 1;
var fmonths = smonths - bmonths;
}
else
{
var fmonths = smonths - bmonths;
}
var fyear = syear - byear;
document.getElementById('patientAge').value = fyear+' years '+fmonths+' months '+fdays+' days';
}
答案 13 :(得分:3)
使用moment.js的另一种可能解决方案:
var moment = require('moment');
var startDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getFullYear() + 5); // Add 5 years to second date
console.log(moment.duration(endDate - startDate).years()); // This should returns 5
答案 14 :(得分:2)
我已经查看了之前显示的示例,并且它们并未在所有情况下都有效,因此我制作了自己的脚本。我对此进行了测试,效果非常好。
function getAge(birth) {
var today = new Date();
var curr_date = today.getDate();
var curr_month = today.getMonth() + 1;
var curr_year = today.getFullYear();
var pieces = birth.split('/');
var birth_date = pieces[0];
var birth_month = pieces[1];
var birth_year = pieces[2];
if (curr_month == birth_month && curr_date >= birth_date) return parseInt(curr_year-birth_year);
if (curr_month == birth_month && curr_date < birth_date) return parseInt(curr_year-birth_year-1);
if (curr_month > birth_month) return parseInt(curr_year-birth_year);
if (curr_month < birth_month) return parseInt(curr_year-birth_year-1);
}
var age = getAge('18/01/2011');
alert(age);
答案 15 :(得分:1)
Get the age (years, months and days) from the date of birth with 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);
}
答案 16 :(得分:0)
这个问题已经超过 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('');
答案 17 :(得分:0)
这是一种计算年龄的简单方法:
//dob date dd/mm/yy
var d = 01/01/1990
//today
//date today string format
var today = new Date(); // i.e wed 04 may 2016 15:12:09 GMT
//todays year
var todayYear = today.getFullYear();
// today month
var todayMonth = today.getMonth();
//today date
var todayDate = today.getDate();
//dob
//dob parsed as date format
var dob = new Date(d);
// dob year
var dobYear = dob.getFullYear();
// dob month
var dobMonth = dob.getMonth();
//dob date
var dobDate = dob.getDate();
var yearsDiff = todayYear - dobYear ;
var age;
if ( todayMonth < dobMonth )
{
age = yearsDiff - 1;
}
else if ( todayMonth > dobMonth )
{
age = yearsDiff ;
}
else //if today month = dob month
{ if ( todayDate < dobDate )
{
age = yearsDiff - 1;
}
else
{
age = yearsDiff;
}
}
答案 18 :(得分:0)
还有两个选择:
// Int Age to Date as string YYY-mm-dd
function age_to_date(age)
{
try {
var d = new Date();
var new_d = '';
d.setFullYear(d.getFullYear() - Math.abs(age));
new_d = d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate();
return new_d;
} catch(err) {
console.log(err.message);
}
}
// Date string (YYY-mm-dd) to Int age (years old)
function date_to_age(date)
{
try {
var today = new Date();
var d = new Date(date);
var year = today.getFullYear() - d.getFullYear();
var month = today.getMonth() - d.getMonth();
var day = today.getDate() - d.getDate();
var carry = 0;
if (year < 0)
return 0;
if (month <= 0 && day <= 0)
carry -= 1;
var age = parseInt(year);
age += carry;
return Math.abs(age);
} catch(err) {
console.log(err.message);
}
}
答案 19 :(得分:0)
var now = DateTime.Now;
var age = DateTime.Now.Year - dob.Year;
if (now.Month < dob.Month || now.Month == dob.Month && now.Day < dob.Day) age--;
答案 20 :(得分:0)
伙计们,对我来说很完美。
getAge(birthday) {
const millis = Date.now() - Date.parse(birthday);
return new Date(millis).getFullYear() - 1970;
}
答案 21 :(得分:0)
您可以将其用于表格中的年龄限制-
function dobvalidator(birthDateString){
strs = birthDateString.split("-");
var dd = strs[0];
var mm = strs[1];
var yy = strs[2];
var d = new Date();
var ds = d.getDate();
var ms = d.getMonth();
var ys = d.getFullYear();
var accepted_age = 18;
var days = ((accepted_age * 12) * 30) + (ms * 30) + ds;
var age = (((ys - yy) * 12) * 30) + ((12 - mm) * 30) + parseInt(30 - dd);
if((days - age) <= '0'){
console.log((days - age));
alert('You are at-least ' + accepted_age);
}else{
console.log((days - age));
alert('You are not at-least ' + accepted_age);
}
}
答案 22 :(得分:0)
对我来说,这是最优雅的方式:
const getAge = (birthDateString) => {
const today = new Date();
const birthDate = new Date(birthDateString);
const yearsDifference = today.getFullYear() - birthDate.getFullYear();
if (
today.getMonth() < birthDate.getMonth() ||
(today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())
) {
return yearsDifference - 1;
}
return yearsDifference;
};
console.log(getAge('2018-03-12'));
答案 23 :(得分:0)
我来不及了,但是我发现这是计算出生日期的最简单方法。
$(document).ready(init);
function init()
{
writeYears("myage", 0, Age());
$(".captcha").click(function()
{
reloadCaptcha();
});
}
function Age()
{
var birthday = new Date(1997, 02, 01), //Year, month, 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 );
}
}
HTML标记:
<span id="myage"></span>
希望这会有所帮助。
答案 24 :(得分:0)
我相信有时在这种情况下可读性更为重要。除非我们要验证1000个字段,否则这应该足够准确且快速:
function is18orOlder(dateString) {
const dob = new Date(dateString);
const dobPlus18 = new Date(dob.getFullYear() + 18, dob.getMonth(), dob.getDate());
return dobPlus18 .valueOf() <= Date.now();
}
// Testing:
console.log(is18orOlder('01/01/1910')); // true
console.log(is18orOlder('01/01/2050')); // false
// When I'm posting this on 10/02/2020, so:
console.log(is18orOlder('10/08/2002')); // true
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();
}
答案 25 :(得分:0)
采用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>
答案 26 :(得分:0)
我使用逻辑而不是数学来使用这种方法。 它精确而快速。 参数是人生日的年,月,日。 它将人的年龄作为整数返回。
function calculateAge(year, month, day) {
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getUTCMonth() + 1;
var currentDay = currentDate.getUTCDate();
// You need to treat the cases where the year, month or day hasn't arrived yet.
var age = currentYear - year;
if (currentMonth > month) {
return age;
} else {
if (currentDay >= day) {
return age;
} else {
age--;
return age;
}
}
}
答案 27 :(得分:0)
我知道这是一个非常古老的主题但是我想把这个我写的实现用于找到我认为更准确的年龄。
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 ) ;
}
当然你可以调整它以适应其他格式的参数。希望这有助于寻找更好解决方案的人。
答案 28 :(得分:-1)
从日期选择器计算年龄
$('#ContentPlaceHolder1_dob').on('changeDate', function (ev) {
$(this).datepicker('hide');
//alert($(this).val());
var date = formatDate($(this).val()); // ('2010/01/18') to ("1990/4/16"))
var age = getAge(date);
$("#ContentPlaceHolder1_age").val(age);
});
function formatDate(input) {
var datePart = input.match(/\d+/g),
year = datePart[0], // get only two digits
month = datePart[1], day = datePart[2];
return day + '/' + month + '/' + year;
}
// alert(formatDate('2010/01/18'));
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
答案 29 :(得分:-1)
function change(){
setTimeout(function(){
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var newdate = year + "/" + month + "/" + day;
var entered_birthdate = document.getElementById('birth_dates').value;
var birthdate = new Date(entered_birthdate);
var birth_year = birthdate.getUTCFullYear();
var birth_month = birthdate.getUTCMonth() + 1;
var birth_date = birthdate.getUTCDate();
var age_year = (year-birth_year);
var age_month = (month-birth_month);
var age_date = ((day-birth_date) < 0)?(31+(day-birth_date)):(day-birth_date);
var test = (birth_year>year)?true:((age_year===0)?((month<birth_month)?true:((month===birth_month)?(day < birth_date):false)):false) ;
if (test === true || (document.getElementById("birth_dates").value=== "")){
document.getElementById("ages").innerHTML = "";
} else{
var age = (age_year > 1)?age_year:( ((age_year=== 1 )&&(age_month >= 0))?age_year:((age_month < 0)?(age_month+12):((age_month > 1)?age_month: ( ((age_month===1) && (day>birth_date) ) ? age_month:age_date) ) ));
var ages = ((age===age_date)&&(age!==age_month)&&(age!==age_year))?(age_date+"days"):((((age===age_month+12)||(age===age_month)&&(age!==age_year))?(age+"months"):age_year+"years"));
document.getElementById("ages").innerHTML = ages;
}
}, 30);
};
答案 30 :(得分:-1)
请参阅此示例,您可以从此处获取全年的月份信息
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
var da = today.getDate() - birthDate.getDate();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
if(m<0){
m +=12;
}
if(da<0){
da +=30;
}
return age+" years "+ Math.abs(m) + "months"+ Math.abs(da) + " days";
}
alert('age: ' + getAge("1987/08/31"));
[http://jsfiddle.net/tapos00/2g70ue5y/][1]
答案 31 :(得分:-1)
我有一个很好的答案,虽然它不是我的代码。不幸的是我忘记了原帖。
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);
答案 32 :(得分:-1)
使用momentjs“fromNow”方法, 这允许您使用格式化日期,即:03/15/1968
var dob = document.getElementByID("dob");
var age = moment(dob.value).fromNow(true).replace(" years", "");
//fromNow(true) => suffix "ago" is not displayed
//but we still have to get rid of "years";
作为原型版
String.prototype.getAge = function() {
return moment(this.valueOf()).fromNow(true).replace(" years", "");
}
答案 33 :(得分:-1)
又一个解决方案:
/**
* Calculate age by birth date.
*
* @param int birthYear Year as YYYY.
* @param int birthMonth Month as number from 1 to 12.
* @param int birthDay Day as number from 1 to 31.
* @return int
*/
function getAge(birthYear, birthMonth, birthDay) {
var today = new Date();
var birthDate = new Date(birthYear, birthMonth-1, birthDay);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
答案 34 :(得分:-1)
这是我的修改:
function calculate_age(date) {
var today = new Date();
var today_month = today.getMonth() + 1; //STRANGE NUMBERING //January is 0!
var age = today.getYear() - date.getYear();
if ((today_month > date.getMonth() || ((today_month == date.getMonth()) && (today.getDate() < date.getDate())))) {
age--;
}
return age;
};
答案 35 :(得分:-1)
这是我能提出的最简单,最准确的解决方案:
Date.prototype.getAge = function (date) {
if (!date) date = new Date();
return ~~((date.getFullYear() + date.getMonth() / 100
+ date.getDate() / 10000) - (this.getFullYear() +
this.getMonth() / 100 + this.getDate() / 10000));
}
这是一个将考虑2月29日的样本 - &gt; 2月28日一年。
Date.prototype.getAge = function (date) {
if (!date) date = new Date();
var feb = (date.getMonth() == 1 || this.getMonth() == 1);
return ~~((date.getFullYear() + date.getMonth() / 100 +
(feb && date.getDate() == 29 ? 28 : date.getDate())
/ 10000) - (this.getFullYear() + this.getMonth() / 100 +
(feb && this.getDate() == 29 ? 28 : this.getDate())
/ 10000));
}
它甚至适用于负面年龄!
答案 36 :(得分:-1)
如果年龄仅出于显示目的(可能不是100%准确),但下面的答案是可行的方法,但是至少可以更容易地绕过头
function age(birthdate){
return Math.floor((new Date().getTime() - new Date(birthdate).getTime()) / 3.154e+10)
}
答案 37 :(得分:-2)
$("#birthday").change(function (){
var val=this.value;
var current_year=new Date().getFullYear();
if(val!=null){
var Split = val.split("-");
var birth_year=parseInt(Split[2]);
if(parseInt(current_year)-parseInt(birth_year)<parseInt(18)){
$("#maritial_status").attr('disabled', 'disabled');
var val2= document.getElementById("maritial_status");
val2.value = "Not Married";
$("#anniversary").attr('disabled', 'disabled');
var val1= document.getElementById("anniversary");
val1.value = "NA";
}else{
$("#maritial_status").attr('disabled', false);
$("#anniversary").attr('disabled', false);
}
}
});
答案 38 :(得分:-2)
我在这里测试的所有答案(大约一半)认为2000-02-29到2001-02-28是零年,当2000-02-29到2001-03-01时它很可能应该是1一年零一天。这是一个修复它的 getYearDiff 函数。它仅适用于d0 < d1
:
function getYearDiff(d0, d1) {
d1 = d1 || new Date();
var m = d0.getMonth();
var years = d1.getFullYear() - d0.getFullYear();
d0.setFullYear(d0.getFullYear() + years);
if (d0.getMonth() != m) d0.setDate(0);
return d0 > d1? --years : years;
}
答案 39 :(得分:-2)
这是我修改过的尝试(传入函数而不是日期对象的字符串):
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'));
答案 40 :(得分:-3)
试试这个:
$('#Datepicker').change(function(){
var $bef = $('#Datepicker').val();
var $today = new Date();
var $before = new Date($bef);
var $befores = $before.getFullYear();
var $todays = $today.getFullYear();
var $bmonth = $before.getMonth();
var $tmonth = $today.getMonth();
var $bday = $before.getDate();
var $tday = $today.getDate();
if ($bmonth>$tmonth)
{$('#age').val($todays-$befores);}
if ($bmonth==$tmonth)
{
if ($tday > $bday) {$('#age').val($todays-$befores-1);}
else if ($tday <= $bday) {$('#age').val($todays-$befores);}
}
else if ($bmonth<$tmonth)
{ $('#age').val($todays-$befores-1);}
})