Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format number of seconds as mm:ss in Angular 2

Tags:

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?

like image 672
Chris Avatar asked Sep 05 '17 12:09

Chris


1 Answers

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);     }  } 
like image 156
Poul Kruijt Avatar answered Oct 26 '22 15:10

Poul Kruijt