简体   繁体   English

将 angular2 组件或 pipe 中的分钟转换为小时

[英]Convert minutes to hours in angular2 component or pipe

In my application storing the duration value in minutes in back end and displaying the data in front end if duration value is below 1 hour in minutes and the same value is equal to above 1 hour in hours.在我的应用程序中,在后端存储持续时间值(以分钟为单位),如果持续时间值低于 1 小时(以分钟为单位)并且相同的值等于 1 小时以上(以小时为单位),则在前端显示数据。

<strong *ngIf="event.eventDuration > 0 && event.eventDuration/60 < 1">{{event.eventDuration}} Minutes<br/></strong>
<strong *ngIf="event.eventDuration > 0 && event.eventDuration/60 >= 1">{{event.eventDuration/60}} Hour(s)<br/></strong>

Is this best way or write component function and return the value from the function?这是最好的方法还是编写组件 function 并从 function 返回值? also component functions are calling too many times if we call from element attribute.如果我们从元素属性调用,组件函数也会调用太多次。

I would create a pipe like this...我会创建一个这样的管道......

@Pipe({
  name: 'myTime'
})
export class MyTimePipe implements PipeTransform {
  transform(value: number): string {
     if(value > 0 && value/60 < 1) {
       return value + ' Minutes';

     } else {
       return value/60 + ' Hour(s)';
     }
  }
}

and use it in your template as follows:并在您的模板中使用它,如下所示:

{{event.eventDuration | myTime}}
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'm2h'
})
export class MinutesToHours implements PipeTransform {
  transform(value: number): string {
    let hours = Math.floor(value / 60);
    let minutes = Math.floor(value % 60);
    return hours + ' hrs ' + minutes + ' mins';
  }
}

Another Way without using PIPE不使用 PIPE 的另一种方式

    transformMinute(value: number): string {
    let hours = Math.floor(value / 60);
    let minutes = Math.floor(value % 60);
    return hours + ' hrs ' + minutes + ' mins';
  }

at HTML在 HTML

{{transformMinute(event.eventDuration)}}
TimeConversion(TimeValue: number): string {

    let hours = Math.floor(TimeValue/ 60);

    let minutes = Math.floor(TimeValue% 60);

    let seconds= Math.floor(TimeValue% 60);

    return hours + ':' + minutes + ':' + seconds ;
}

This will return ---> example: 5:25:12这将返回 ---> 示例:5:25:12

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM