Format 33546001 seconds into a readable format of 1 year, 23 days, 6 hours, 20 minutes and 1 second.
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秒
If the hour, minute and second are less than 10, you need to add 0, which is as follows:
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秒
Sometimes we also need to format a point in time in the past, how long has passed since now, as follows:
Convert the posting time of the article or comment to, just, 10 minutes ago....
You can refer to the following article
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。