- 想要达成的效果是这样的:将36600秒转成4天5小时40分0秒或者是101小时40分0秒,会存在这种情况就是后台返回给我们的单位是秒,但是我们需要渲染成X天X小时这种格式。
- 代码如下:
<div>{{ newTime }}</div>
</template>
<script>
export default {
name: "APP",
data() {
return {
newTime: ""
};
},
methods: {
handleTime(time, format = "{d}天{h}小时{m}分钟{s}秒", unit = "s") {
if (!time) return "";
if (arguments.length === 0) {
return null;
}
if (time < 0) return time;
const times = unit === "ms" ? Math.floor(time / 1000) : time;
// 毫秒
let ms = unit === "ms" ? time % 1000 : 0;
// 天
let d = Math.floor(times / (24 * 3600));
// 小时
let h = Math.floor((times % (24 * 3600)) / 3600);
// 分
let m = Math.floor((times % 3600) / 60);
// 秒
let s = Math.floor((times % 3600) % 60);
// 判断你想要输出的格式
if (!/d+/g.test(format)) {
h += d * 24; //如果格式不需要显示天,那一天就相当于24小时
}
if (!/h+/g.test(format)) {
m += h * 60;
}
if (!/m+/g.test(format.replace("ms", ""))) {
s += m * 60;
}
if (!/s+/g.test(format)) {
ms += s * 1000;
}
const formatTime = { ms, d, h, m, s };
const filterTime = format
.split("{").filter(item => {
return formatTime[item[0]] !== 0; //将formatTime中为0的过滤掉
})
.join("{");
const resultTime = filterTime.replace(/{([ymdhisa])}/g, (result, key) => {
return formatTime[key]; //replace用法,这里可以将result和key 打印一下就更加容易理解,函数的返回值作为替换字符串
});//通俗点就是将filterTime中的ymdhisa替换成formatTime[key]
return resultTime;
},
getTime() {
this.newTime = this.handleTime(366000, "{d}天{h}时{m}分");//根据需求传入相应的格式即可
}
},
created() {
this.getTime();
}
};
</script>
<style lang="scss" scoped>
</style>
3.效果: