Birthday Calculation

JavaScript performance comparison

Revision 2 of this test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var dateString = "1992-01-13";
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/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;
}
pending…
Optimized code
calcAge(dateString);

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

function OPAge(dob) {
  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--;
  }
  return age;
}
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment