将时间间隔以秒为单位转换成更易读的forms

我需要一个代码片段来将秒数给定的时间转换成一些人类可读的forms。 该函数应该接收一个数字并输出如下的string:

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

在Royi的帮助下,我们得到了以可读的forms输出时间间隔的代码:

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

如果您对现有的JavaScript库感兴趣,那么您可能需要检查moment.js 。

更具体地说,你的问题相关的moment.js段是持续时间 。

以下是一些如何利用它来实现您的任务的例子:

 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 humanize()方法,你可以免费获得多语言支持。

如果要显示确切的时间信息,则可以利用为此目的而创build的moment.js的时刻精确范围插件:

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

有一点需要注意的是,目前的moment.js不支持持续时间对象的周/天(以星期为单位)。

希望这可以帮助!

尝试以下方法

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

注意:

  • 平常的一年有365天。 一个闰年有366天,所以你需要额外的检查,如果这是你的问题。
  • 夏令时类似的问题。 时间改变的时候有些日子有23天,有的时候有25个小时。

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

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

这将需要毫秒作为一个int,并给你一个JSON对象,其中包含您可能需要的所有信息

方式更简单,可读性强。

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

这使:

“3小时25分45秒”

根据@ 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(); } 

关于我的好的一点是, if s没有重复,并且不会给你0年0天30分1秒的例子。

例如:

forHumans(60)输出1 minute

forHumans(3600)输出1 hour

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

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

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

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

“放样”

此function以这种格式输出秒数:11h 22m,1y 244d,42m 4s等设置最大variables以显示任意数量的标识符。

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

只显示你所需要的,而不是第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; }; 

在Dan答案的帮助下,如果您想计算创build后时间(从数据库中应该检索为UTC)到用户系统时间之间的差异,然后显示已用时间,可以使用下面的function

 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'); 

这是一个解决scheme。 稍后,您可以按“:”拆分并获取数组的值

  /** * 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); 

我是对象的粉丝,所以我从https://metacpan.org/pod/Time::Seconds

用法:

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

我清理了一些其他的答案,提供了很好的'10秒前'样式string:

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

按照@Dan类似的方法,我修改了@Royi Namir的代码,用逗号和和输出一个string:

 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(numminutes + " 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秒以内停止警告。