JS – Calculate your age

It sounds like a simple task: write some JavaScript to get the current date, compare it to your birthday, and display the difference, thereby calculating your age. Looking up ways to perform such a task, however, is anything but simple. Most of the answers you will find are composed of either large blocks of code in involving converting milliseconds to whatever format you want, with most implementations not accounting for leap years, while others reference some obscure, outdated JavaScript library (and 99% of the time, using a single function in a large library is inefficient and wasteful). You may quickly give up hope performing such a calculation because everything is too complex.

I too was looking for a way to calculate my age using JavaScript, but all attempts to find a pre-made solution ended as described above. I finally decided to write my own function to calculate my age. In this tutorial, I will be walking you through the code so how you can use it yourself! Time to get calculating! 😀

We are going to be covering a lot of concepts here, so a bit of prior JavaScript knowledge will help. Of course, I will provide resources for further explanations and documentation. If you need a quick way to execute the code, find the JavaScript scratchpad and console in your browser’s developer tools or use the Codecademy Labs JavaScript console. 😉

First off, we need to collect the current date. We will use the built-in Date() function to do this. Since we want it to be correct in every time zone around the world, we will use a UTC timestamp.

var curDate = new Date(),
    now     = {
      year: curDate.getUTCFullYear(),
      // UTC month value is zero-based
      month: curDate.getUTCMonth() + 1,
      day: curDate.getUTCDate()
    },
    diff = now.year % date.year;

What we are doing here is creating a new Date instance and assigning it to the variable curDate. Next, we are creating an object called now containing three properties: year, month, and day. They are assigned their respective values by extracting the UTC year, month, and day values from curDate. As noted by the inline comment, the UTC month value starts at zero. This means January is be expressed as 0, February 1, March 2, and so on. We offset it to match the Georgian calendar by adding a 1.

Also in this snippet, we calculate the difference between the two years using the remainder operator and assign it to diff.

Next, we will define the date. For fun, we will use my birthday, 13 March, 1995. We will do this by taking the above code and wrapping in a yearDifference() function:

function yearDifference(date) {
  "use strict";
  var curDate = new Date(),
      now     = {
        year: curDate.getUTCFullYear(),
        // UTC month value is zero-based
        month: curDate.getUTCMonth() + 1,
        day: curDate.getUTCDate()
      },
      diff = now.year % date.year;
}

As you can see, the function has a parameter date, whose properties matches the now object. Thus when we call the function we will pass the following object:

{
  year: 1995,
  month: 3,
  day: 13
}

However, our function is imperfect. Depending on your birthday and current month/day, diff may not correct. Further, once the year changes, the value will increase even if your birthday has not yet passed. To remedy this, we need to perform some validation using the following condition:

// Do not update the date unless it is time
if (now.month < date.month ||
    now.month === date.month && now.day < date.day) {
  diff -= 1;
}
return diff;

The condition is composed of two clauses that prevents the calculation from turning over too soon. The first simply checks if the current month is less then the given month. The second clauses reads “If the current month is equal to the given month AND the current day is less than the given day.” When one of these clauses is true, we subtract a 1 from diff, thereby giving us my proper age. Finally, we return diff to the caller (remember, all this code is wrapped inside the yearDifference() function).

console.log(yearDifference({ year: 1995, month: 3, day: 13 }));

This line passes the required date object with my birthday (as described earlier) and displays the final result in the browser’s console. You will want to change this to the appropriate action (document.querySelector(), $.html(), etc.) for your site. 😉

Here is the final code all put together with an added JSDoc annotation.

If you are wondering if this method is accurate, the answer is yes. We are not dealing with time and leap years do not affect your birthday (that is, unless you were born on February 29), only day, month, and year integers. 🙂

Congratulations! You now know how to accurately calculate your age using JavaScript! Feel free to use this bit of code on your site. If you find it useful, please send me a shout out on Twitter, and do not hesitate to ask any questions you may have. 😀

-Caleb

Advertisements

2 thoughts on “JS – Calculate your age

Triangular Reactions

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s