我有一个开始日期、时间和结束日期、时间,而且我正在找出旅行的总持续时间。输出以毫秒为单位,我需要将其转换为小时格式。通过在这里搜索其他答案,我尝试了以下但没有结果。
<md-cell *mdCellDef="let row"> {{row?.duration | formatDuration}} </md-cell>
和ts文件:
export class StoppageComponent implements OnInit {
constructor() {
}
ngOnInit() {
}
filter('formatDuration', function () {
return function (input) {
var totalHours, totalMinutes, totalSeconds, hours, minutes, seconds, result='';
totalSeconds = input / 1000;
totalMinutes = totalSeconds / 60;
totalHours = totalMinutes / 60;
seconds = Math.floor(totalSeconds) % 60;
minutes = Math.floor(totalMinutes) % 60;
hours = Math.floor(totalHours) % 60;
if (hours !== 0) {
result += hours+':';
if (minutes.toString().length == 1) {
minutes = '0'+minutes;
}
}
result += minutes+':';
if (seconds.toString().length == 1) {
seconds = '0'+seconds;
}
result += seconds;
return result;
};
});
}
我认为错误出在 ts 文件上,因为我是 angular 的新手。
有没有不用函数直接用管道转换的?
最佳答案
其他答案看起来很复杂,终于自己找到了解决方案..
HTML 作为,
<md-cell *mdCellDef="let row"> {{getFormathours(row?.duration)}} </md-cell>
和 ts,
getFormathours(input) {
var totalHours, totalMinutes, totalSeconds, hours, minutes, seconds, result='';
totalSeconds = input / 1000;
totalMinutes = totalSeconds / 60;
totalHours = totalMinutes / 60;
seconds = Math.floor(totalSeconds) % 60;
minutes = Math.floor(totalMinutes) % 60;
hours = Math.floor(totalHours) % 60;
console.log (hours + ' : ' + minutes + ' : ' + seconds);
if (hours !== 0) {
result += hours+' hr:';
if (minutes.toString().length == 1) {
minutes = '0'+minutes;
}
}
result += minutes+' min';
if (seconds.toString().length == 1) {
seconds = '0'+seconds;
}
result += seconds;
return result;
}
这给出了我需要的确切输出,并根据我的问题提供了更清晰的解决方案。无论如何,我也感谢其他人的回答。
关于javascript - 毫秒到小时格式的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46583910/