Search code examples
javascriptutc

Calculate Age JavaScript


How is this age function calculated?

Specifically where does the "7656656e5" value used come from?

I'm looking to calculate age for someone born 03/31/1994

    Age = function() {
    var e, o;
    return renderAgeLoop = function() {
      setInterval(renderAge, 100)
    }, renderAge = function() {
      var n = 7656656e5, //Where does this value come from?
        r = new Date,
        t = r - n,
        a = t / 315569e5;
      e = $("#major"), o = $("#minor");
      var i = a.toFixed(9).toString().split(".");

      var d = new Date();
      console.log(d.toUTCString())

      e.text(i[0]), o.text(i[1])
    }, {
      renderAgeLoop: renderAgeLoop
    }
  }

Solution

  • This line here

    var n = 7656656e5
    

    Is a method of expressing numbers in JavaScript. I believe it refers to scientific notation.

    It takes the number 7656656 and multiplies that by 10 ^ 5, which is the e5.

    If you run it in your console (Chrome Developer Tools) you will see something like this

    => 765665600000
    

    As for what that number represents, I noticed you are comparing that value with new Date(). So it probably represents the number of miliseconds since the January 1st, 1970 epoch.

    Anyways, if you are looking to calculate age, here's a better approach.

    var startTime = new Date("1990").getTime()
    var currentTime = new Date().getTime()
    
    var age = currentTime - startTime/Math.floor(1000 * 60 * 60 * 24 * 365)
    

    Best possible solution though is checking out the excellent library MomentJS. It's much easier to work with.

    http://momentjs.com/