很多时候,前端展示的数据都是后端处理好的,但是,也有极个别特殊的情况,那就是后端直接返回时间戳,那么就需要前端封装函数,把时间戳转化成时分秒。
// 封装函数,时间戳转时长
const formatSeconds = (value: number) => {
var theTime = parseInt(value); // 秒
var theTime1 = 0; // 分
var theTime2 = 0; // 小时
if (theTime > 60) {
theTime1 = parseInt(theTime / 60);
theTime = parseInt(theTime % 60);
if (theTime1 > 60) {
theTime2 = parseInt(theTime1 / 60);
theTime1 = parseInt(theTime1 % 60);
}
}
var result = "" + parseInt(theTime) + "秒";
if (theTime1 > 0) {
result = "" + parseInt(theTime1) + "分" + result;
}
if (theTime2 > 0) {
result = "" + parseInt(theTime2) + "小时" + result;
}
return result;
};
例如:我传入1722331930,输出结果为478小时32分11秒