把 33546001秒 格式化为 1年23天6小时20分1秒这种易读格局。
function secondsToString(seconds) {
if (seconds === 0) return '0'
let y = Math.floor(seconds / 31536000);
let d = Math.floor((seconds % 31536000) / 86400);
let h = Math.floor(((seconds % 31536000) % 86400) / 3600);
let m = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
let s = (((seconds % 31536000) % 86400) % 3600) % 60;
let result = '';
if (y) result += y + "年";
if (d) result += d + "天";
if (h) result += h + "小时";
if (m) result += m + "分";
if (s) result += s + "秒";
return result;
}
const b = secondsToString(33546001)
console.log('b:', b)
// 1年23天6小时20分1秒
如果时分秒有余10须要补0,就是下边这样:
function secondsToString(seconds) {
if (seconds === 0) return '0'
let y = Math.floor(seconds / 31536000);
let d = Math.floor((seconds % 31536000) / 86400);
let h = Math.floor(((seconds % 31536000) % 86400) / 3600);
let m = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
let s = (((seconds % 31536000) % 86400) % 3600) % 60;
let result = '';
if (y) result += y + "年";
if (d) result += d + "天";
if (h) {
h<10?result += '0'+h + "小时":result += h + "小时";
}
if (m) {
m<10?result += '0'+m + "分":result += m + "分";
}
if (s) {
s<10?result += '0'+s + "秒":result += s + "秒";
}
return result;
}
const a = secondsToString(33546001)
console.log('a:', a)
// a: 1年23天06小时20分01秒
有时咱们还须要格式化过来的某个工夫点,间隔当初曾经过来多久,如下:
把文章或者评论的 公布工夫 转换成,刚刚,10分钟前….
能够参考上面这篇文章
格式化公布工夫
发表回复