我正在尝试在我的 Angular 应用程序上以自定义格式显示一些日期:我想看到“1小时前”、“2天前”......而不是实际时间,所以我正在考虑使用过滤器来执行此操作。
我的日期存储在 MongoDb 中,因此我以 ISODate 形式接收它们:
ISODate("2014-03-13T10:48:02.991Z")
基本上我想将此函数应用于我的日期:
function timeSince(ts){
now = new Date();
ts = new Date(ts*1000);
var delta = now.getTime() - ts.toString().getTime();
delta = delta/1000; //us to s
var ps, pm, ph, pd, min, hou, sec, days;
if(delta<=59){
ps = (delta>1) ? "s": "";
return delta+" second"+ps
}
if(delta>=60 && delta<=3599){
min = Math.floor(delta/60);
sec = delta-(min*60);
pm = (min>1) ? "s": "";
ps = (sec>1) ? "s": "";
return min+" minute"+pm+" "+sec+" second"+ps;
}
if(delta>=3600 && delta<=86399){
hou = Math.floor(delta/3600);
min = Math.floor((delta-(hou*3600))/60);
ph = (hou>1) ? "s": "";
pm = (min>1) ? "s": "";
return hou+" hour"+ph+" "+min+" minute"+pm;
}
if(delta>=86400){
days = Math.floor(delta/86400);
hou = Math.floor((delta-(days*86400))/60/60);
pd = (days>1) ? "s": "";
ph = (hou>1) ? "s": "";
return days+" day"+pd+" "+hou+" hour"+ph;
}
}
如何简单地使用过滤器来做到这一点?
谢谢
最佳答案
您只需要创建一个 filter
返回该函数。
myModule.filter('prettyTime', function(){
return function(ts){
//Your code here
};
});
假设您的 $scope
上有一些 Date 对象:
<span>{{time | prettyTime}}</span>
这是一个工作演示:http://jsfiddle.net/jwcarroll/ARc65/
关于javascript - 使用过滤器以自定义格式设置日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22409458/