为了账号安全,请及时绑定邮箱和手机立即绑定

将以秒为单位的时间间隔转换为更易理解的形式

将以秒为单位的时间间隔转换为更易理解的形式

Smart猫小萌 2019-11-13 15:33:21
我需要一个代码段,用于将以秒为单位的时间转换成某种人类可读的形式。该函数应接收一个数字并输出如下字符串:34 seconds 12 minutes 4 hours 5 days 4 months1 year无需格式化,将采用硬编码格式。
查看完整描述

3 回答

?
杨魅力

TA贡献1811条经验 获得超6个赞

在Royi的帮助下,我们获得了以人类可读形式输出时间间隔的代码:


function millisecondsToStr (milliseconds) {

    // TIP: to find current time in milliseconds, use:

    // var  current_time_milliseconds = new Date().getTime();


    function numberEnding (number) {

        return (number > 1) ? 's' : '';

    }


    var temp = Math.floor(milliseconds / 1000);

    var years = Math.floor(temp / 31536000);

    if (years) {

        return years + ' year' + numberEnding(years);

    }

    //TODO: Months! Maybe weeks? 

    var days = Math.floor((temp %= 31536000) / 86400);

    if (days) {

        return days + ' day' + numberEnding(days);

    }

    var hours = Math.floor((temp %= 86400) / 3600);

    if (hours) {

        return hours + ' hour' + numberEnding(hours);

    }

    var minutes = Math.floor((temp %= 3600) / 60);

    if (minutes) {

        return minutes + ' minute' + numberEnding(minutes);

    }

    var seconds = temp % 60;

    if (seconds) {

        return seconds + ' second' + numberEnding(seconds);

    }

    return 'less than a second'; //'just now' //or other string you like;

}


查看完整回答
反对 回复 2019-11-13
  • 3 回答
  • 0 关注
  • 493 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号