Birthday Calculation (v9)

Revision 9 of this benchmark created 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
Mathematical
getAge(new Date(dateString));

function getAge(thisDate) {
    var date = new Date();
    return ~~((date.getFullYear() + date.getMonth() / 100 + date.getDate() / 10000) - (thisDate.getFullYear() + thisDate.getMonth() / 100 + thisDate.getDate() / 10000));
}
ready
Mathematical with Math.floor
getAge(new Date(dateString));

function getAge(thisDate) {
    var date = new Date();
    return Math.floor((date.getFullYear() + date.getMonth() / 100 + date.getDate() / 10000) - (thisDate.getFullYear() + thisDate.getMonth() / 100 + thisDate.getDate() / 10000));
}
ready

Revisions

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