Format number of seconds as mm:ss in Angular 2

Chris picture Chris · Sep 5, 2017 · Viewed 17k times · Source

I am displaying a number of seconds that counts down from 3600 to 0.

<div class="time-box" *ngIf="p.value.playerTimer > 0">{{ p.value.playerTimer }}</div>

I would like to format the number of seconds as minutes:seconds

I hoped to be able to use DatePipe - https://angular.io/api/common/DatePipe

<div class="time-box" *ngIf="p.value.playerTimer > 0">{{ p.value.playerTimer | date:'mmss' }}</div>

But this doesn't work as it expects p.value.playerTimer to be a date object or number of seconds since the epoch.

Is there another way to achieve this?

Answer

Poul Kruijt picture Poul Kruijt · Sep 5, 2017

You have to write your own pipe. Something like this. Be aware though, it's untested and does not take into account any strange input it might receive. Also it does not have any leading zeros, but hey, now you got something to do as well:

@Pipe({
  name: 'minuteSeconds'
})
export class MinuteSecondsPipe implements PipeTransform {

    transform(value: number): string {
       const minutes: number = Math.floor(value / 60);
       return minutes + ':' + (value - minutes * 60);
    }

}