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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8211744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:08:40  来源:igfitidea点击:

Convert time interval given in seconds into more human readable form

javascriptdatetimetime

提问by Dan

I need a code snippet for converting amount of time given by number of seconds into some human readable form. The function should receive a number and output a string like this:

我需要一个代码片段,用于将按秒数给出的时间量转换为某种人类可读的形式。该函数应该接收一个数字并输出一个像这样的字符串:

34 seconds 
12 minutes 
4 hours 
5 days 
4 months
1 year

No formatting required, hard-coded format will go.

无需格式化,硬编码格式将消失。

采纳答案by Dan

With help of Royi we've got code that outputs time interval in a human readable form:

在 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;
}

回答by Royi Namir

 function secondsToString(seconds)
{
var numyears = Math.floor(seconds / 31536000);
var numdays = Math.floor((seconds % 31536000) / 86400); 
var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600);
var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
var numseconds = (((seconds % 31536000) % 86400) % 3600) % 60;
return numyears + " years " +  numdays + " days " + numhours + " hours " + numminutes + " minutes " + numseconds + " seconds";

}

回答by urish

If you are interested in an existing javascript library that does the job very well, you may want to check moment.js.

如果您对可以很好地完成工作的现有 javascript 库感兴趣,您可能需要查看moment.js

More specifically, the relevant moment.js piece for your question is durations.

更具体地说,与您的问题相关的 moment.js 是durations

Here are some examples of how you can take advantage of it to achieve your task:

以下是一些如何利用它来完成任务的示例:

var duration = moment.duration(31536000);

// Using the built-in humanize function:
console.log(duration.humanize());   // Output: "9 hours"
console.log(duration.humanize(true));   // Output: "in 9 hours"

moment.js has built-in support for 50+ human languages, so if you use the humanize()method you get multi-language support for free.

moment.js 内置了对 50 多种人类语言的支持,因此如果您使用该humanize()方法,您将免费获得多语言支持。

If you want to display the exact time information, you can take advantage of the moment-precise-rangeplug-in for moment.js that was created exactly for this purpose:

如果您想显示确切的时间信息,您可以利用专门为此目的创建的 moment.js的moment-precise-range插件:

console.log(moment.preciseDiff(0, 39240754000);
// Output: 1 year 2 months 30 days 5 hours 12 minutes 34 seconds

One thing to note is that currently moment.js does not support weeks / days (in week) for duration object.

需要注意的一件事是,当前 moment.js 不支持持续时间对象的周/天(以周为单位)。

Hope this helps!

希望这可以帮助!

回答by Martin

Took a swing based on @Royi's response:

根据@Royi 的回应进行了一次挥杆:

/**
 * Translates seconds into human readable format of seconds, minutes, hours, days, and years
 * 
 * @param  {number} seconds The number of seconds to be processed
 * @return {string}         The phrase describing the the amount of time
 */
function forHumans ( seconds ) {
    var levels = [
        [Math.floor(seconds / 31536000), 'years'],
        [Math.floor((seconds % 31536000) / 86400), 'days'],
        [Math.floor(((seconds % 31536000) % 86400) / 3600), 'hours'],
        [Math.floor((((seconds % 31536000) % 86400) % 3600) / 60), 'minutes'],
        [(((seconds % 31536000) % 86400) % 3600) % 60, 'seconds'],
    ];
    var returntext = '';

    for (var i = 0, max = levels.length; i < max; i++) {
        if ( levels[i][0] === 0 ) continue;
        returntext += ' ' + levels[i][0] + ' ' + (levels[i][0] === 1 ? levels[i][1].substr(0, levels[i][1].length-1): levels[i][1]);
    };
    return returntext.trim();
}

Nice thing about mine is that there is no repetitive ifs, and won't give you 0 years 0 days 30 minutes 1 secondfor example.

我的好处是没有重复的ifs,例如不会给你0 年 0 天 30 分 1 秒

For example:

例如:

forHumans(60)outputs 1 minute

forHumans(60)产出 1 minute

forHumans(3600)outputs 1 hour

forHumans(3600)产出 1 hour

and forHumans(13559879)outputs 156 days 22 hours 37 minutes 59 seconds

forHumans(13559879)输出156 days 22 hours 37 minutes 59 seconds

回答by Reporter

Try following:

尝试以下操作:

seconds = ~~(milliseconds / 1000);
minutes = ~~(seconds / 60);
hours = ~~(minutes / 60);
days = ~~(hours / 24);
weeks = ~~(days / 7);
year = ~~(days / 365);

Note:

笔记:

  • A usual year has 365 days. A leap year has 366 days, so you need additional check if this is an issue for you.
  • The similar problem with daylight saving. Some days have 23 and some 25 hours when time's changed.
  • 通常一年有 365 天。闰年有 366 天,因此您需要额外检查这是否是您的问题。
  • 夏令时的类似问题。当时间改变时,有些日子有 23 小时和大约 25 小时。

Conclusion: this is a rude but small and simple snippet :)

结论:这是一个粗鲁但又小又简单的片段:)

回答by Zibri

Way more simple and readable.

方式更简单和可读。

milliseconds = 12345678;
mydate=new Date(milliseconds);
humandate=mydate.getUTCHours()+" hours, "+mydate.getUTCMinutes()+" minutes and "+mydate.getUTCSeconds()+" second(s)";

Which gives:

这使:

"3 hours, 25 minutes and 45 second(s)"

“3 小时 25 分 45 秒”

回答by galv

millisToTime = function(ms){

    x = ms / 1000;
    seconds = Math.round(x % 60);
    x /= 60;
    minutes = Math.round(x % 60);
    x /= 60;
    hours = Math.round(x % 24);
    x /= 24;
    days = Math.round(x);

    return {"Days" : days, "Hours" : hours, "Minutes" : minutes, "Seconds" : seconds};
}

This will take milliseconds as an int, and give you an JSON object containing all the info you could need

这将花费毫秒作为一个整数,并为您提供一个包含您可能需要的所有信息的 JSON 对象

回答by Nofi

To Convert time in millisecond to human readable format.

将时间以毫秒为单位转换为人类可读的格式。

 function timeConversion(millisec) {

        var seconds = (millisec / 1000).toFixed(1);

        var minutes = (millisec / (1000 * 60)).toFixed(1);

        var hours = (millisec / (1000 * 60 * 60)).toFixed(1);

        var days = (millisec / (1000 * 60 * 60 * 24)).toFixed(1);

        if (seconds < 60) {
            return seconds + " Sec";
        } else if (minutes < 60) {
            return minutes + " Min";
        } else if (hours < 24) {
            return hours + " Hrs";
        } else {
            return days + " Days"
        }
    }

"Out Put Sample"

“输出样品”

回答by Dmitry Sheiko

Thanks to @Dan / @ Royi for the logic. However the implementation doesn't build time string like XX days, XX mins. I adjusted their code a bit:

感谢@Dan / @ Royi 的逻辑。但是,该实现不会构建像 XX 天,XX 分钟这样的时间字符串。我稍微调整了他们的代码:

function millisecondsToStr( milliseconds ) {
    let temp = milliseconds / 1000;
    const years = Math.floor( temp / 31536000 ),
          days = Math.floor( ( temp %= 31536000 ) / 86400 ),
          hours = Math.floor( ( temp %= 86400 ) / 3600 ),
          minutes = Math.floor( ( temp %= 3600 ) / 60 ),
          seconds = temp % 60;

    if ( days || hours || seconds || minutes ) {
      return ( years ? years + "y " : "" ) +
      ( days ? days + "d " : "" ) +
      ( hours ? hours + "h " : ""  ) +
      ( minutes ? minutes + "m " : "" ) +
      Number.parseFloat( seconds ).toFixed( 2 ) + "s";
    }

    return "< 1s";
}

When one runs it

当一个人运行它

console.log("=", millisecondsToStr( 1540545689739 - 1540545684368 ));
console.log("=", millisecondsToStr( 351338536000 ));

The results look like:

结果如下:

= 5.37s
= 11y 51d 10h 2m 16.00s

回答by Obaluaiyê

function millisecondsToString(milliseconds) {
    var oneHour = 3600000;
    var oneMinute = 60000;
    var oneSecond = 1000;
    var seconds = 0;
    var minutes = 0;
    var hours = 0;
    var result;

    if (milliseconds >= oneHour) {
        hours = Math.floor(milliseconds / oneHour);
    }

    milliseconds = hours > 0 ? (milliseconds - hours * oneHour) : milliseconds;

    if (milliseconds >= oneMinute) {
        minutes = Math.floor(milliseconds / oneMinute);
    }

    milliseconds = minutes > 0 ? (milliseconds - minutes * oneMinute) : milliseconds;

    if (milliseconds >= oneSecond) {
        seconds = Math.floor(milliseconds / oneSecond);
    }

    milliseconds = seconds > 0 ? (milliseconds - seconds * oneSecond) : milliseconds;

    if (hours > 0) {
        result = (hours > 9 ? hours : "0" + hours) + ":";
    } else {
        result = "00:";
    }

    if (minutes > 0) {
        result += (minutes > 9 ? minutes : "0" + minutes) + ":";
    } else {
        result += "00:";
    }

    if (seconds > 0) {
        result += (seconds > 9 ? seconds : "0" + seconds) + ":";
    } else {
        result += "00:";
    }

    if (milliseconds > 0) {
        result += (milliseconds > 9 ? milliseconds : "0" + milliseconds);
    } else {
        result += "00";
    }

    return result;
}