Birthday Calculation (v22)

Revision 22 of this benchmark created by jjyepez on


Setup

var dateString = "1992-01-13";

Test runner

Ready to run.

Testing in
TestOps/sec
Accepted Answer
getAge(dateString);

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;
}
ready
Optimized code
calcAge(dateString);

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

function edad_segun_fecha(fecha_nacimiento) {
  var arr_fecha = fecha_nacimiento.split('-');
  var dia = arr_fecha[2],
    mes = arr_fecha[1] - 1,
    ano = arr_fecha[0];
  var fecha = new Date(parseInt(ano), parseInt(mes), parseInt(dia), 0, 0, 0, 0);
  var hoy = new Date();
  var dif = (Date.parse(hoy) - Date.parse(fecha)) / 31557600000;

  return dif;
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.