1

How can you pipe a number in Angular that comes in minutes, like 450 to look like this 07:30:00 in hours. I only managed to make it look like this 7.5h using the following pipe:

transform(value: number): string {
        if(value > 0 && value/60 < 1) {
          return value + ' m';

        } else {
          return value/60 + 'h';
        }
     }
jBuchholz
  • 1,742
  • 2
  • 17
  • 25
Andrea
  • 11
  • 1
  • 5
  • Please define some case how the pipe will works. If input >0 && < 60? If input > 24 * 60? What is the pattern it use. Also you can refer to built-in DatePipe https://angular.io/api/common/DatePipe – Mr. Brickowski May 13 '20 at 06:58

1 Answers1

1
transform(minutes: number): string {
    const hours = Math.floor(minutes/60);
    const minutesLeft = minutes % 60;
    return `${hours < 10 ? '0' : ''}${hours}:${minutesLeft < 10 ? '0': ''}${minutesLeft}:00`
}

The same as JavaScript-Snippet:

    function transform(minutes) {
        const hours = Math.floor(minutes/60);
        const minutesLeft = minutes % 60;
        return `${hours < 10 ? '0' : ''}${hours}:${minutesLeft < 10 ? '0': ''}${minutesLeft}:00`
    }
    
    console.log(transform(450));

This should do the trick. You get the number of hours by dividing by 60 (and rounding down to the full hour) and the number of minutes left is the modulo minutes % 60.

With the comparisons hours < 10 you add leading zeros if needed.

jBuchholz
  • 1,742
  • 2
  • 17
  • 25