Chr*_*ris 12 angular2-template angular
我显示的秒数从3600减少到0.
<div class="time-box" *ngIf="p.value.playerTimer > 0">{{ p.value.playerTimer }}</div>
Run Code Online (Sandbox Code Playgroud)
我想将秒数格式化为分钟:秒
我希望能够使用DatePipe - https://angular.io/api/common/DatePipe
<div class="time-box" *ngIf="p.value.playerTimer > 0">{{ p.value.playerTimer | date:'mmss' }}</div>
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为它预计p.value.playerTimer是一个日期对象或自纪元以来的秒数.
还有另一种方法来实现这一目标吗?
Pie*_*Duc 24
你必须自己编写管道.像这样的东西.但请注意,它未经测试,并未考虑可能收到的任何奇怪输入.它也没有任何前导零,但是,嘿,现在你还有事要做:
@Pipe({
name: 'minuteSeconds'
})
export class MinuteSecondsPipe implements PipeTransform {
transform(value: number): string {
const minutes: number = Math.floor(value / 60);
return minutes + ':' + (value - minutes * 60);
}
}
Run Code Online (Sandbox Code Playgroud)
Ash*_*yan 24
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: 3600 * 1000
<div class="time-box" *ngIf="p.value.playerTimer > 0">
{{ p.value.playerTimer * 1000 | date:'mm:ss' }}
</div>
Run Code Online (Sandbox Code Playgroud)
here is the Stackblitz example https://stackblitz.com/edit/date-pipe-example-nhafvx
maybe someone will come in handy
将所有答案放在一起加上HTML中的示例用法:
来自markau和PierreDuc:
@Pipe({
name: 'minuteSeconds'
})
export class MinuteSecondsPipe implements PipeTransform {
transform(value: number): string {
const minutes: number = Math.floor(value / 60);
return minutes.toString().padStart(2, '0') + ':' +
(value - minutes * 60).toString().padStart(2, '0');
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的HTML中:
<div ...>{{ p.value.playerTimer | minuteSeconds }}
Run Code Online (Sandbox Code Playgroud)
例如,如果p.value.playerTimer = 127,它将显示02:07
小智 6
对于任何寻求更进一步并支持时间的答案的人:
const toHoursMinutesSeconds = totalSeconds => {
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
let result = `${minutes
.toString()
.padStart(1, '0')}:${seconds.toString().padStart(2, '0')}`;
if (!!hours) {
result = `${hours.toString()}:${minutes
.toString()
.padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
return result;
};
Run Code Online (Sandbox Code Playgroud)
生产:
toHoursMinutesSeconds(55);
'0:55'
toHoursMinutesSeconds(679);
'11:19'
toHoursMinutesSeconds(12345);
'3:25:45'
toHoursMinutesSeconds(123456);
'34:17:36'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9395 次 |
| 最近记录: |