JavaScript把秒格式为易读形式
文章目录
把 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分钟前....
可以参考下面这篇文章
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论