Convert birthday to age in angularjs

Hitesh Modha picture Hitesh Modha · Jul 22, 2014 · Viewed 25.4k times · Source

I want to display age of all my users to grid. I am reading data from facebook.I am not storing it at anywhere.

i am displaying date like :

{{ friend.birthday }}

How can i display age instead of displaying birthday.

if it is possible to create filters than how to create filter and how to apply it.

Answer

pixelbits picture pixelbits · Jul 22, 2014

You can implement a function:

Controller:

$scope.calculateAge = function calculateAge(birthday) { // birthday is a date
    var ageDifMs = Date.now() - birthday.getTime();
    var ageDate = new Date(ageDifMs); // miliseconds from epoch
    return Math.abs(ageDate.getUTCFullYear() - 1970);
}

HTML

{{ calculateAge(friend.birthday) }}

Or a filter:

app.filter('ageFilter', function() {
     function calculateAge(birthday) { // birthday is a date
         var ageDifMs = Date.now() - birthday.getTime();
         var ageDate = new Date(ageDifMs); // miliseconds from epoch
         return Math.abs(ageDate.getUTCFullYear() - 1970);
     }

     return function(birthdate) { 
           return calculateAge(birthdate);
     }; 
});

HTML

{{ friend.birthday | ageFilter }}

Age algorithm taken from this SO answer.

[EDIT] If the age is less than 1 year, and you want to show months, you can modify the ageFilter to calculate the month difference:

app.filter('ageFilter', function() {
     function calculateAge(birthday) { // birthday is a date
         var ageDifMs = Date.now() - birthday.getTime();
         var ageDate = new Date(ageDifMs); // miliseconds from epoch
         return Math.abs(ageDate.getUTCFullYear() - 1970);
     }
     function monthDiff(d1, d2) {
       if (d1 < d2){
        var months = d2.getMonth() - d1.getMonth();
        return months <= 0 ? 0 : months;
       }
       return 0;
     }       
     return function(birthdate) { 
           var age = calculateAge(birthdate);
           if (age == 0)
             return monthDiff(birthdate, new Date()) + ' months';
           return age;
     }; 
});

Demo Plunker - Age Function
Demo Plunker - Age Filter
Demo Plunker - Age Filter with Months < 1 year