本文介绍了定制管用于计算angular2中相对时间的过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在学习过程中,我遇到了创建自定义管道,因此我认为这会有所帮助。
During the learning process, I came across Creation of Custom Pipe, so I thought this will help.
推荐答案
下面是自定义管道的代码。
Below is the code for custom pipe.
import{PipeTransform,Pipe} from '@angular/core';
@Pipe({
name:'relativeTime'
})
export class RelativeTimeFilterPipe implements PipeTransform{
transform(inputDate:string):string{
var current = new Date().valueOf();
var input = new Date(parseInt(inputDate)).valueOf();
var msPerMinute = 60 * 1000;
var msPerHour = msPerMinute * 60;
var msPerDay = msPerHour * 24;
var msPerMonth = msPerDay * 30;
var msPerYear = msPerDay * 365;
var elapsed = current - input;
if (elapsed < msPerMinute) {
return Math.round(elapsed / 1000) + ' seconds ago';
}
else if (elapsed < msPerHour) {
return Math.round(elapsed / msPerMinute) + ' minutes ago';
}
else if (elapsed < msPerDay) {
return Math.round(elapsed / msPerHour) + ' hours ago';
}
else if (elapsed < msPerMonth) {
return 'approximately ' + Math.round(elapsed / msPerDay) + ' days ago';
}
else if (elapsed < msPerYear) {
return 'approximately ' + Math.round(elapsed / msPerMonth) + ' months ago';
}
else {
console.log('inside the if condition', elapsed);
return 'approximately ' + Math.round(elapsed / msPerYear) + ' years ago';
}
}
}
LIVE DEMO
这篇关于定制管用于计算angular2中相对时间的过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!