Custom Pipe | filter for calculating relative time in angular2

 ̄綄美尐妖づ 提交于 2019-12-02 18:34:50

问题


During the learning process, I came across Creation of Custom Pipe, so I thought this will help.


回答1:


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



来源:https://stackoverflow.com/questions/41528844/custom-pipe-filter-for-calculating-relative-time-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!