定制管|用于计算角度2的相对时间的过滤器

时间:2017-01-08 02:28:39

标签: angular angular2-pipe angular2-custom-pipes

在学习过程中,我遇到了创建自定义管道,所以我认为这会有所帮助。

2 个答案:

答案 0 :(得分:4)

以下是自定义管道的代码。

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

答案 1 :(得分:0)

这是一个异步相对日期管道。它会在您观看屏幕时更新相对时间,它甚至不是不纯的管道,因此速度更快!另一个很棒的事情是,相对时间更新都通过使用 cron 调度程序同时发生。

import { OnDestroy, Pipe, PipeTransform } from '@angular/core'
import { timeAgo } from '../../../utils/date-utils'
import { BehaviorSubject } from 'rxjs'
import * as schedule from 'node-schedule'

@Pipe({name: 'timeAgo'})
export class TimeAgoPipe implements PipeTransform, OnDestroy {

  sub: BehaviorSubject<string>
  job: schedule.Job
  date: Date

  constructor() {
    this.sub = new BehaviorSubject<string>(null)
    this.job = schedule.scheduleJob('*/10 * * * * *', () => { // updates every 10 secs at 1:10 1:20 1:30 etc
      if (this.date) this.sub.next(timeAgo(this.date))
    })
  }

  transform(date: Date | number): BehaviorSubject<string> {
    setTimeout(() => {
      this.date = new Date(date)
      this.sub.next(timeAgo(this.date))
    })

    return this.sub
  }

  ngOnDestroy(): void {
    this.job.cancel()
  }
}

模板用法如下所示:

<span>{{ activity.date | timeAgo | async }}</span>

这是 timeAgo 函数:

import TimeAgo from 'javascript-time-ago'
import en from 'javascript-time-ago/locale/en'

TimeAgo.addDefaultLocale(en)
const ago = new TimeAgo()

export const timeAgo = (date) => {
  return ago.format(date)
}