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

Javascript 将以秒为单位的时间间隔转换为更易于阅读的形式,javascript,datetime,time,Javascript,Datetime,Time,我需要一个代码片段,用于将以秒数表示的时间量转换为人类可读的形式。函数应接收一个数字并输出如下字符串: 34 seconds 12 minutes 4 hours 5 days 4 months 1 year 无需格式化,硬编码格式将被删除。请尝试以下操作: function secondsToString(seconds) { var numyears = Math.floor(seconds / 31536000); var numdays = Math.floor((secon

我需要一个代码片段,用于将以秒数表示的时间量转换为人类可读的形式。函数应接收一个数字并输出如下字符串:

34 seconds 
12 minutes 
4 hours 
5 days 
4 months
1 year
无需格式化,硬编码格式将被删除。

请尝试以下操作:

 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";

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

  • 通常一年有365天。闰年有366天,所以你需要额外检查这是否是你的问题
  • 夏令时也存在类似的问题。当时间改变时,有些日子有23小时,有些日子有25小时

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

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

此功能以这种格式输出秒数:11h 22m、1y 244d、42m 4s等 设置max变量以显示所需的标识符

function secondsToString (seconds) {

var years = Math.floor(seconds / 31536000);
var max =2;
var current = 0;
var str = "";
if (years && current<max) {
    str+= years + 'y ';
    current++;
}
var days = Math.floor((seconds %= 31536000) / 86400);
if (days && current<max) {
    str+= days + 'd ';
    current++;
}
var hours = Math.floor((seconds %= 86400) / 3600);
if (hours && current<max) {
    str+= hours + 'h ';
    current++;
}
var minutes = Math.floor((seconds %= 3600) / 60);
if (minutes && current<max) {
    str+= minutes + 'm ';
    current++;
}
var seconds = seconds % 60;
if (seconds && current<max) {
    str+= seconds + 's ';
    current++;
}

return str;
}
函数秒到字符串(秒){
变量年份=数学下限(秒/31536000);
var max=2;
无功电流=0;
var str=“”;

if(years&¤t这是一个解决方案。以后您可以按“:”分割并获取数组的值

 /**
 * Converts milliseconds to human readeable language separated by ":"
 * Example: 190980000 --> 2:05:3 --> 2days 5hours 3min
 */
function dhm(t){
    var cd = 24 * 60 * 60 * 1000,
        ch = 60 * 60 * 1000,
        d = Math.floor(t / cd),
        h = '0' + Math.floor( (t - d * cd) / ch),
        m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
    return [d, h.substr(-2), m.substr(-2)].join(':');
}

//Example
var delay = 190980000;                   
var fullTime = dhm(delay);
console.log(fullTime);

这将以毫秒为整数,并为您提供一个JSON对象,其中包含您可能需要的所有信息,以仅显示您需要的信息,而不是第0天、第0小时

formatTime = function(time) {
        var ret = time % 1000 + ' ms';
        time = Math.floor(time / 1000);
        if (time !== 0) {
            ret = time % 60 + "s "+ret;
            time = Math.floor(time / 60);
            if (time !== 0) {
                ret = time % 60 + "min "+ret;
                time = Math.floor(time / 60);
                if (time !== 0) {
                    ret = time % 60 + "h "+ret;
                     ...
                }
            }           
        }
        return ret;
    };

我非常喜欢对象,所以我从

用法:

var human_readable = new TimeSeconds(986543).pretty(); // 11 days, 10 hours, 2 minutes, 23 seconds

;(function(w) {
  var interval = {
    second: 1,
    minute: 60,
    hour: 3600,
    day: 86400,
    week: 604800,
    month: 2629744, // year / 12
    year: 31556930 // 365.24225 days
  };

  var TimeSeconds = function(seconds) { this.val = seconds; };

  TimeSeconds.prototype.seconds = function() { return parseInt(this.val); };
  TimeSeconds.prototype.minutes = function() { return parseInt(this.val / interval.minute); };
  TimeSeconds.prototype.hours = function() { return parseInt(this.val / interval.hour); };
  TimeSeconds.prototype.days = function() { return parseInt(this.val / interval.day); };
  TimeSeconds.prototype.weeks = function() { return parseInt(this.val / interval.week); };
  TimeSeconds.prototype.months = function() { return parseInt(this.val / interval.month); };
  TimeSeconds.prototype.years = function() { return parseInt(this.val / interval.year); };

  TimeSeconds.prototype.pretty = function(chunks) {
    var val = this.val;
    var str = [];

    if(!chunks) chunks = ['day', 'hour', 'minute', 'second'];

    while(chunks.length) {
      var i = chunks.shift();
      var x = parseInt(val / interval[i]);
      if(!x && chunks.length) continue;
      val -= interval[i] * x;
      str.push(x + ' ' + (x == 1 ? i : i + 's'));
    }

    return str.join(', ').replace(/^-/, 'minus ');
  };

  w.TimeSeconds = TimeSeconds;
})(window);

如果您对一个能够很好地完成这项工作的现有javascript库感兴趣,您可能需要检查一下

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

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

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内置支持50多种人类语言,因此如果您使用
humanize()
方法,您将免费获得多语言支持

如果您想显示准确的时间信息,可以利用正是为此目的创建的moment.js插件:

console.log(moment.preciseDiff(0, 39240754000);
// Output: 1 year 2 months 30 days 5 hours 12 minutes 34 seconds
需要注意的一点是,目前moment.js不支持duration对象的周/天(以周为单位)


希望这能有所帮助!

我清理了其他答案中的一个,提供了很好的“10秒前”样式字符串:

function msago (ms) {
    function suffix (number) { return ((number > 1) ? 's' : '') + ' ago'; }
    var temp = ms / 1000;
    var years = Math.floor(temp / 31536000);
    if (years) return years + ' year' + suffix(years);
    var days = Math.floor((temp %= 31536000) / 86400);
    if (days) return days + ' day' + suffix(days);
    var hours = Math.floor((temp %= 86400) / 3600);
    if (hours) return hours + ' hour' + suffix(hours);
    var minutes = Math.floor((temp %= 3600) / 60);
    if (minutes) return minutes + ' minute' + suffix(minutes);
    var seconds = Math.floor(temp % 60);
    if (seconds) return seconds + ' second' + suffix(seconds);
    return 'less then a second ago';
};

更简单易读

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

3小时25分45秒


在Dan answer的帮助下,如果您想计算创建后的时间(从DB中应该检索为UTC)和用户系统时间之间的差异,然后向他们显示经过的时间,可以使用下面的函数

function dateToStr(input_date) {
  input_date= input_date+" UTC";
  // convert times in milliseconds
  var input_time_in_ms = new Date(input_date).getTime();
  var current_time_in_ms = new Date().getTime();
  var elapsed_time = current_time_in_ms - input_time_in_ms;

  function numberEnding (number) {
      return (number > 1) ? 's' : '';
  }

  var temp = Math.floor(elapsed_time / 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;
}
用法

var str = dateToStr('2014-10-05 15:22:16');

根据@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();
}
/**
*将秒转换为人类可读的秒、分钟、小时、天和年格式
* 
*@param{number}seconds要处理的秒数
*@return{string}描述时间量的短语
*/
人类功能(秒){
风险值水平=[
[数学地板(秒/31536000),“年”],
[数学地板((秒数%31536000)/86400),“天”],
[数学地板(((秒%31536000)%86400)/3600),“小时”],
[数学地板(((秒%31536000)%86400)%3600)/60),“分钟”],
[((秒%31536000)%86400)%3600)%60,“秒”],
];
var returntext='';
对于(变量i=0,max=levels.length;i
我的优点是没有重复的
if
s,并且不会给你0年0天30分钟1秒

例如:

适用于人类(60)
输出
1分钟

forHumans(3600)
输出
1小时


和人类的
(13559879)
输出
156天22小时37分59秒

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

 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"
        }
    }
函数时间转换(毫秒){
变量秒=(毫秒/1000).toFixed(1);
var分钟=(毫秒/(1000*60)).toFixed(1);
var小时=(毫秒/(1000*60*60)).toFixed(1);
变量天数=(毫秒/(1000*60*60*24)).toFixed(1);
如果(秒<60){
返回秒数+秒数;
}否则,如果(分钟<60){
返回分钟数+分钟数;
}否则,如果(小时<24小时){
返回小时数+小时数;
}否则{
返回天数+“天”
}
}

按照与@Dan类似的方法,我修改了@Royi Namir的代码,以输出带有逗号和的字符串:

secondsToString = function(seconds) {
    var numdays, numhours, nummilli, numminutes, numseconds, numyears, res;
    numyears = Math.floor(seconds / 31536000);
    numdays = Math.floor(seconds % 31536000 / 86400);
    numhours = Math.floor(seconds % 31536000 % 86400 / 3600);
    numminutes = Math.floor(seconds % 31536000 % 86400 % 3600 / 60);
    numseconds = seconds % 31536000 % 86400 % 3600 % 60;
    nummilli = seconds % 1.0;
    res = [];
    if (numyears > 0) {
        res.push(numyears + " years");
    }
    if (numdays > 0) {
        res.push(numdays + " days");
    }
    if (numhours > 0) {
        res.push(numhours + " hours");
    }
    if (numminutes > 0) {
        res.push(numminutes + " minutes");
    }
    if (numseconds > 0) {
        res.push(numseconds + " seconds");
    }
    if (nummilli > 0) {
        res.push(nummilli + " milliseconds");
    }
    return [res.slice(0, -1).join(", "), res.slice(-1)[0]].join(res.length > 1 ? " and " : "");
};
它没有句号,因此可以在其后添加句子,如下图所示:

perform: function(msg, custom, conn) {
    var remTimeLoop;
    remTimeLoop = function(time) {
        if (time !== +custom[0]) {
            msg.reply((secondsToString(time)) + " remaining!");
        }
        if (time > 15) {
            return setTimeout((function() {
                return remTimeLoop(time / 2);
            }), time / 2);
        }
    };
    // ...
    remTimeLoop(+custom[0]);
}
其中,
custom[0]
是等待的总时间;它将持续将时间除以2,警告计时器结束前的剩余时间,并在时间低于15秒时停止警告。

函数secondsToTimeString(输入){
function secondsToTimeString(input) {
  let years = 0, days = 0, hours = 0, minutes = 0, seconds = 0;
  let ref = [31536000,86400,3600,60,1];
  for (let i = 0;i < ref.length;i++) {
    let val = ref[i];
    while (val <= input) {
      input -= val;
      if (i === 0) years++;
      if (i === 1) days++;
      if (i === 2) hours++;
      if (i === 3) minutes++;      
      if (i === 4) seconds++;      
    }
  return {years, days, hours, minutes, seconds};
  }
假设年=0,天=0,小时=0,分钟=0,秒=0; 设ref=[31536000864003600,60,1]; for(设i=0;i虽然(val多亏了@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";
}
结果如下:

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

还有Intl.RelativeTimeFormat API,最新版本的Chrome和Firefox支持该API

举几个例子:

let rtf = new Intl.RelativeTimeFormat("en");
rtf.format(-1, "day"); // 'yesterday'
rtf.format(-2, 'day'); // '2 days ago'
rtf.format(13.37, 'second'); // 'in 13.37 seconds'
而且里面还有很多

更简单的方法。你可以分别选择几年和几天。

这是我的看法

您可以在游戏中随意使用它


可能重复的是和否,我想有一个很好的JavaScript解决方案…秒是一种人类可读的形式。好吧,“213123秒”不是那么可读。你可以提出一个更好的标题!如果你添加复数检查(年/年),它会
console.log("=", millisecondsToStr( 1540545689739 - 1540545684368 ));
console.log("=", millisecondsToStr( 351338536000 ));
= 5.37s
= 11y 51d 10h 2m 16.00s
let rtf = new Intl.RelativeTimeFormat("en");
rtf.format(-1, "day"); // 'yesterday'
rtf.format(-2, 'day'); // '2 days ago'
rtf.format(13.37, 'second'); // 'in 13.37 seconds'
function java_seconds_to_readable(seconds)
{
    var numhours = Math.floor(seconds / 3600);
    var numminutes = Math.floor((seconds / 60) % 60);
    var numseconds = seconds % 60;
    return numhours + ":" + numminutes + ":" + numseconds;
}
// This returns a string representation for a time interval given in milliseconds
// that appeals to human intuition and so does not care for leap-years,
// month length irregularities and other pesky nuisances.
const human_millis = function (ms, digits=1) {
    const levels=[
      ["ms", 1000],
      ["sec", 60],
      ["min", 60],
      ["hrs", 24],
      ["days", 7],
      ["weeks", (30/7)], // Months are intuitively around 30 days
      ["months", 12.1666666666666666], // Compensate for bakari-da in last step
      ["years", 10],
      ["decades", 10],
      ["centuries", 10],
      ["millenia", 10],
    ];
    var value=ms;
    var name="";
    var step=1;
    for(var i=0, max=levels.length;i<max;++i){
        value/=step;
        name=levels[i][0];
        step=levels[i][1];
        if(value < step){
            break;
        }
    }
    return value.toFixed(digits)+" "+name;
}

console.clear();
console.log("---------");
console.log(human_millis(1));
console.log(human_millis(10));
console.log(human_millis(100));
console.log(human_millis(1000));
console.log(human_millis(1000*60));
console.log(human_millis(1000*60*60));
console.log(human_millis(1000*60*60*24));
console.log(human_millis(1000*60*60*24*7));
console.log(human_millis(1000*60*60*24*30));
console.log(human_millis(1000*60*60*24*365));
console.log(human_millis(1000*60*60*24*365*10));
console.log(human_millis(1000*60*60*24*365*10*10));
console.log(human_millis(1000*60*60*24*365*10*10*10));
console.log(human_millis(1000*60*60*24*365*10*10*10*10));
let name : string | number = "";
    let step : string | number =1;
    for(var i=0, max=levels.length;i<max;++i){
        value/= step as number;
        name=levels[i][0];
        step=levels[i][1];
        if(value < step){
            break;
        }
        
    }
"---------"
"1.0 ms"
"10.0 ms"
"100.0 ms"
"1.0 sec"
"1.0 min"
"1.0 hrs"
"1.0 days"
"1.0 weeks"
"1.0 months"
"1.0 years"
"1.0 decades"
"1.0 centuries"
"1.0 millenia"
"10.0 millenia"