从后台获取时间戳的毫秒数,前台需要动态显示其单位,例如我们从后台api获取数据时间戳为’239462.464681666’,想要显示为’66 h 36 m 20.575672791 s’:
js代码:
在构造器中,这里使用ES6的箭头表达式;
this.formatUptime = (uptime) => {
if (uptime) {
let decimalUT = uptime.split('.')[1];//小数部分
let secondUT = parseInt(uptime);
let minuteUT, hourUT;
if (secondUT > 60) {
minuteUT = parseInt(secondUT / 60);
secondUT = parseInt(secondUT % 60);
if (minuteUT > 60) {
hourUT = parseInt(minuteUT / 60);
minuteUT = parseInt(minuteUT % 60);
}
}
let result = {
hour: 0,
minute: 0,
second: secondUT,
decimal: decimalUT,
};
if (minuteUT > 0) {
result = {
hour: 0,
minute: minuteUT,
second: secondUT,
decimal: decimalUT,
}
}
if (hourUT > 0) {
result = {
hour: hourUT,
minute: minuteUT,
second: secondUT,
decimal: decimalUT,
}
}
return result;
}
}
前台代码
$ctrl.uptime为动态获取的时间戳;这里单位做了颜色特殊显示;
<span ng-if="$ctrl.formatUptime($ctrl.uptime).hour>0">{{$ctrl.formatUptime($ctrl.uptime).hour}}</span>
<span class="health-unit" ng-if="$ctrl.formatUptime($ctrl.uptime).hour>0">h</span>
<span>{{$ctrl.formatUptime($ctrl.uptime).minute}}</span>
<span class="health-unit">m</span> <span>{{$ctrl.formatUptime($ctrl.uptime).second}}.{{$ctrl.formatUptime($ctrl.uptime).decimal}}</span> <span class="health-unit">s</span>
这样我们就可以动态的显示出时、分、秒的格式并且时间单位设置不同样式,完成后效果如下图: