0

how to make a custom pipe in angular 8 to convert second to hours and minutes.

thanks.

<div class="col-2" *ngFor="let movie of moviesList">
  <div class="movie">
    {{ movie.attributes.title }}
    <img [src]="movie.thumbnails.small">
    {{ movie.attributes.duration }} <== second
  </div>
</div>
  • create a pipe class and implement the `transform()` method. checkout angular documentation: https://angular.io/guide/pipes#custom-pipes – x7R5fQ Jun 14 '20 at 16:31
  • yes i already tried that but i dont understand how i can use the Transform(). to convert Second to Hours & Minutes –  Jun 14 '20 at 16:53
  • https://stackoverflow.com/q/37096367/1160794 – David Jun 14 '20 at 16:59

2 Answers2

3

Create a pipe with a name like FormatTime

format-time.pipes.ts

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

@Pipe({name: 'formatTime'})
export class FormatTime implements PipeTransform {
  transform(value: number): string {
    return new Date(value * 1000).toISOString().substr(11, 8)
  }
}

Import and add it to your declarations in the module

...
import { FormatTime } from './format-time.pipes';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent, FormatTime ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Template

<div class="col-2" *ngFor="let movie of moviesList">
  <div class="movie">
    {{ movie.attributes.title }}
    <img [src]="movie.thumbnails.small">
    {{ movie.attributes.duration | formatTime }}
  </div>
</div>
arif08
  • 746
  • 7
  • 15
1

You can create a pipe like below,

@Pipe({
    name: 'secondsTransform'
})
export class SecondsTransformPipe implements PipeTransform {
    constructor() {}

    transform(value: number): string {
        let minutes: number = Math.trunc(value/60);
        let hours: number = 0;
        let seconds: number = value - (minutes*60);

        if (minutes >= 60) {
          hours = Math.trunc(minutes/60);
          minutes = minutes - (hours*60);
        }

        let response: string = "";

        if (hours > 0) {
          response = response + hours + " hours ";
        } 

        if (minutes > 0) {
          response = response + minutes + " minutes ";
        }

        if (seconds > 0) {
          response = response + seconds + " seconds";
        }

        return response;
    }
}

Import the pipe in the module and use it in html as {{seconds|secondsTransform}}

You can refer the below sample which uses pipe to show the seconds in Hours/Minutes/Seconds, https://stackblitz.com/edit/angular-ivy-7jte9o

Ani
  • 370
  • 2
  • 9