日期管道隐藏零

时间:2016-06-23 12:28:12

标签: javascript angular momentjs

我想知道如何修改/创建自己的管道,以便:

  1. 如果小于分钟,则显示秒数
  2. 如果小于1小时,请显示mm:ss
  3. 如果小于1小时,请显示hh:mm:ss
  4. 我知道当我使用时:

    {{ dateObj | date:'hhmmss' }}        // output is '00:00:11' when timestamp is 11s;
    

1 个答案:

答案 0 :(得分:2)

由于Angular管道是一个带有一些装饰器的JS类,你仍然可以直接使用它。在您的情况下,您可以实现自己的管道,它将使用内置的角管道,如下所示:

new DatePipe().transform(myDate, 'hhmmss');

让我们走吧:

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({name: 'my-duration'})
export class MyDurationPipe implements PipeTransform {
  transform(value: Date): string {
    if (/* time difference is less than minute */) { // add your comparison to get minutes
      return new DatePipe().transform(value, 'ss');
    } 
    else if (/* time difference is less than hour */) { // the same for hours etc.
      return new DatePipe().transform(value, 'mm:ss');
    }
    // and so on 
  }
}

然后您可以将它用作常规管道。