转换生日年龄在angularjs [英] Convert birthday to age in angularjs
问题描述
我要显示我的所有用户网龄。我从facebook.I读取数据我不是在任何地方存放。
I want to display age of all my users to grid. I am reading data from facebook.I am not storing it at anywhere.
我正在显示日期,如:
{{ 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.
推荐答案
您可以实现的功能:
控制器:
$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 - 伴月和LT年龄过滤; 1年
Demo Plunker - Age Function
Demo Plunker - Age Filter
Demo Plunker - Age Filter with Months < 1 year
这篇关于转换生日年龄在angularjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!