yyyy restar partir para obtener nacimiento formulario formato fechas fecha edad cronologica con como calcular javascript date

javascript - restar - obtener edad a partir de fecha de nacimiento js



Calcular la edad dada la fecha de nacimiento en el formato AAAAMMDD. (30)

¿Cómo puedo calcular una edad en años, dada una fecha de nacimiento del formato AAAAMMDD? ¿Es posible usar la función Date() ?

Estoy buscando una solución mejor que la que estoy usando ahora:

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);


Adoptando de los mensajes de naveen y OP originales, terminé con un código de método reutilizable que acepta tanto cadenas como objetos JS Date.

Lo llamé gregorianAge() porque este cálculo da exactamente cómo denotamos la edad con el calendario gregoriano. es decir, sin contar el año final si mes y día son anteriores al mes y día del año de nacimiento.

/** * 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>


Aquí está la solución más simple y precisa que podría encontrar:

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)); }

Y aquí hay una muestra que se considerará del 29 de febrero al 28 de febrero por año.

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)); }

Incluso funciona con la edad negativa!


Aquí está mi solución, solo pase una fecha analizable:

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 }


Aquí hay una forma simple de calcular la edad:

//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; } }


Con el momentjs " momentjs " de momentjs, esto le permite trabajar con fecha formateada, es decir: 15/03/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";

Como versión prototipo.

String.prototype.getAge = function() { return moment(this.valueOf()).fromNow(true).replace(" years", "");

}


Con momentjs:

/* The difference, in years, between NOW and 2012-05-07 */ moment().diff(moment(''20120507'', ''YYYYMMDD''), ''years'')


Creo que eso podría ser así:

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

Funciona también con una marca de tiempo.

age(403501000000) //34


Dos opciones más:

// 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); } }


Funciona perfecto para mí, chicos.

getAge(birthday) { const millis = Date.now() - Date.parse(birthday); return new Date(millis).getFullYear() - 1970; }


Hace un tiempo hice una función con ese propósito:

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; }

Toma un objeto Date como entrada, por lo que necesita analizar la cadena de fecha con formato ''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


He comprobado los ejemplos mostrados anteriormente y no funcionaron en todos los casos, y debido a esto hice un guión por mi cuenta. He probado esto, y funciona perfectamente.

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);


He hecho un poco actualizado a una respuesta anterior.

var calculateAge = function(dob) { var days = function(date) { return 31*date.getMonth() + date.getDate(); }, d = new Date(dob*1000), now = new Date(); return now.getFullYear() - d.getFullYear() - ( measureDays(now) < measureDays(d)); }

Espero que ayude: D


Otra solución más:

/** * 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; }


Para probar si el cumpleaños ya pasó o no, defino una función auxiliar Date.prototype.getDoY , que devuelve efectivamente el número del día del año. El resto es bastante autoexplicativo.

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));


Prueba esto.

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; }

Creo que lo único que parecía grosero en su código era la parte de substr .

Fiddle : http://jsfiddle.net/codeandcloud/n33RJ/


Sé que este es un hilo muy antiguo, pero quería incluir esta implementación que escribí para encontrar la edad que creo que es mucho más precisa.

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 ) ; }

Por supuesto, podría adaptar esto para que se ajuste a otros formatos de obtención de parámetros. Espero que esto ayude a alguien que busca una mejor solución.


Solo tuve que escribir esta función por mí mismo: la respuesta aceptada es bastante buena, pero IMO podría usar algo de limpieza. Esto requiere una marca de tiempo de Unix para dob porque ese era mi requisito, pero podría adaptarse rápidamente para usar una cadena:

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)); }

Note que he usado un valor plano de 31 en mi función de medición de días. Todo el cálculo que importa es que el "día del año" sea una medida monótonamente creciente de la marca de tiempo.

Si utiliza una marca de tiempo o una cadena de JavaScript, obviamente querrá eliminar el factor de 1000.


Solución alternativa, porque por qué no:

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; }


Una solución más posible con momentjs :

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


Utilicé este enfoque utilizando la lógica en lugar de las matemáticas. Es preciso y rápido. Los parámetros son el año, mes y día del cumpleaños de la persona. Devuelve la edad de la persona como un entero.

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; } } }


Obtenga la edad (años, meses y días) a partir de la fecha de nacimiento con javascript

Función calcularEdad (años, meses y días)

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"; }

Función 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); }


Importante: esta respuesta no proporciona una respuesta precisa al 100%, se desactiva entre 10 y 20 horas, según la fecha.

No hay mejores soluciones (no en estas respuestas de todos modos). - naveen

Por supuesto, no pude resistir la tentación de aceptar el desafío y hacer una calculadora de cumpleaños más rápida y más corta que la solución actualmente aceptada. El punto principal de mi solución es que las matemáticas son rápidas, por lo que, en lugar de usar bifurcaciones, el modelo de fecha que proporciona javascript para calcular una solución usamos las maravillosas

La respuesta se ve así, y corre ~ 65% más rápido que el de naveen, y es mucho más corto:

function calcAge(dateString) { var birthday = +new Date(dateString); return ~~((Date.now() - birthday) / (31557600000)); }

El número mágico: 31557600000 es 24 * 3600 * 365.25 * 1000, que es la duración de un año, la duración de un año es de 365 días y 6 horas, que es de 0.25 días. Al final i piso el resultado que nos da la edad final.

Aquí están los puntos de referencia: http://jsperf.com/birthday-calculation

Para admitir el formato de datos de OP, puede reemplazar +new Date(dateString);
con +new Date(d.substr(0, 4), d.substr(4, 2)-1, d.substr(6, 2));

Si puede encontrar una solución mejor, por favor comparta! :-)


Limpie la solución de una sola línea ES6 escrita:

const getAge = birthDate => Math.floor((new Date() - new Date(birthDate).getTime()) / 31556925994) // (today is 2018-06-13) getAge(''1994-06-14'') // 23 getAge(''1994-06-13'') // 24

Usando un año de 365.242199 días (porque años bisiestos)


Puede utilizar esto para la restricción de edad en su forma -

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); } }


Yo iría por la legibilidad:

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); }

Descargo de responsabilidad: Esto también tiene problemas de precisión, por lo que tampoco se puede confiar completamente. Puede apagarse por algunas horas, algunos años o durante el horario de verano (dependiendo de la zona horaria).

En su lugar, recomendaría usar una biblioteca para esto, si la precisión es muy importante. También la @Naveens post es probablemente la más precisa, ya que no depende de la hora del día.

Puntos de referencia: http://jsperf.com/birthday-calculation/15


Tengo una respuesta bonita aunque no es mi código. Lamentablemente olvidé el post original.

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);


function clearInfo(date) { date.setFullYear(0); date.setHours(0); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); return date; } function compareDateOnly(date1, date2) { date1 = clearInfo(new Date(date1)); date2 = clearInfo(new Date(date2)); return date1 - date2; } function getAge(date) { var bday = new Date(date); var now = new Date(); var years = now.getFullYear() - bday.getFullYear(); if (compareDateOnly(bday, now) < 0) { //this year birthday past return years; } return years - 1; //not past }

Suponiendo que una persona nazca el 11 de septiembre de 1991, no tendrá 1 año hasta el 12 de septiembre de 1992


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''; }


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; }

Para obtener la edad en que ha entrado la fecha europea:

getAge(''16-03-1989'')


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--;