且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在angularjs中将生日转换为年龄

更新时间:2023-01-26 22:28:31

你可以实现一个功能:

控制器:

$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) }}

或过滤器:

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 }}

年龄算法取自这个 SO 答案.

如果年龄小于 1 岁,并且你想显示月份,你可以修改 ageFilter 来计算月份差异:

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;
     }; 
});

演示 Plunker - 年龄函数
演示 Plunker - 年龄过滤器
演示 Plunker - 月龄过滤器1 年