Birthday Calculation (v13)

Revision 13 of this benchmark created on


Setup

var dateString = "1992-01-13";
  
  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;
  }
  
  function calcAge(dateString) {
    var birthday = +new Date(dateString);
    return ~~((Date.now() - birthday) / (31557600000));
  }
  
  function getDiff(dateString) {
  
      birthday = new Date(dateString);
      var now = new Date();
      var nowYear = now.getFullYear();
      var birthdayYear = birthday.getFullYear();
  
      var birthdayThisYear = new Date(nowYear, birthday.getMonth(), birthday.getDate());
  
      var dif = nowYear - birthdayYear + (birthdayThisYear > now ? -1 : 0);
  
      return dif;
  }

Test runner

Ready to run.

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

ready
Optimized code
calcAge(dateString);

ready
3
getDiff(dateString);
ready

Revisions

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