在angularjs中将生日转换为年龄 [英] Convert birthday to age in angularjs
本文介绍了在angularjs中将生日转换为年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将所有用户的年龄显示到网格中.我正在从 facebook 读取数据.我没有将其存储在任何地方.
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 - 月龄过滤器1 年
这篇关于在angularjs中将生日转换为年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文