【问题标题】:Date pipe to hide zeros隐藏零的日期管道
【发布时间】:2016-06-23 12:28:12
【问题描述】:

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

  1. 如果小于分钟,则显示秒
  2. 如果小于小时,则显示 mm:ss
  3. 如果少于 1 小时,则显示 hh:mm:ss

我知道当我使用时:

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

【问题讨论】:

  • 您没有将日期对象用于 duration 值,是吗?
  • @deceze,我正在使用时间戳
  • 时间戳不是时间跨度。
  • 您想以适合持续时间的方式格式化时间戳,这对我来说似乎很奇怪。 “11”不是有用的时间戳,“0:00:11”是。如果您尝试使用 durations(例如“此操作持续 3m 和 5s”),不要使用日期对象和日期格式。因为日期不会给出您的持续时间超过 24 小时。这可能是一个实际问题,也可能不是,但它在概念上是错误的,最终很容易导致问题。

标签: javascript angular momentjs


【解决方案1】:

由于 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 
  }
}

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

【讨论】:

  • minutehour 在您的ifs 中来自哪里?
  • 看看 cmets - 这不是实际代码,而只是想法。我不知道作者到底想如何传递变量(作为日期或时间戳)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多