Search code examples
angularangular2-template

Format number of seconds as mm:ss in Angular 2


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?


Solution

  • Angular Date Pipe works with number value too, But please note: Only with milliseconds.

    If you want to get mm:ss(00:00) you need to convert your number value to milliseconds. In your case it should be: 3600 * 1000

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

    NOTE:

    • Add 'UTC' to get results for local time zones
    • use date: 'HH:mm:ss':'UTC' to use 24 hour format. if not 30 mins will be displayed as 12:30:00

    here is the Stackblitz example https://stackblitz.com/edit/date-pipe-example-nhafvx

    maybe someone will come in handy