关于javascript:JavaScript把秒格式为易读形式

7次阅读

共计 1147 个字符,预计需要花费 3 分钟才能阅读完成。

把 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 分钟前 ….

能够参考上面这篇文章

格式化公布工夫

正文完
 0