Convert the time interval specified in seconds to a more readable form

I need a piece of code to convert the amount of time specified by the number of seconds into some readable form. The function should receive a number and output a string as follows:

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

No formatting required, the format is hard-coded.

+62
javascript datetime time
Nov 21 '11 at 12:24
source share
19 answers

With Royi, we have a code that displays a time interval in a readable form :

 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; } 
+64
Nov 21 '11 at
source share
  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"; } 
+71
Nov 21 '11 at 12:27
source share

If you are interested in the existing javascript library that does this job very well, you can check moment.js .

In particular, the appropriate moment. js for your question durations .

Here are some examples of how you can use it to accomplish 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 free support for several languages.

If you want to display accurate time information, you can use the moment-precise-range plugin for the .js moment, which was created just for this purpose

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

It should be noted that currently moment.js does not support weeks / days (per week) for an object of duration.

Hope this helps!

+45
Mar 15 '14 at 10:48
source share

Took a hesitation based on @Royi's answer:

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

The good thing about mine is that there are no duplicate if s, and it will not give you 0 years 0 days 30 minutes 1 second , for example.

For example:

forHumans(60) outputs 1 minute

forHumans(3600) outputs 1 hour

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

+16
Dec 14 '15 at 15:31
source share

Try the following:

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

Note:

  • A typical year has 365 days. A leap year has 366 days, so you need extra checking if this is a problem for you.
  • A similar problem with summer savings. Some days have 23 and around 25 hours when time has changed.

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

+15
Nov 21 '11 at 12:34
source share
 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}; } 

It takes milliseconds as an int and gives you a JSON object containing all the information you might need

+13
Jul 10 '13 at 8:19
source share

The path is simpler and more understandable.

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

What gives:

"3 hours, 25 minutes and 45 seconds"

+13
Mar 29 '14 at 12:51
source share
 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; } 
+3
Feb 06 '13 at
source share

Convert time in milliseconds to a 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" } } 

+3
Jan 19 '16 at 6:56
source share

Thanks @ Dan / @ Royi for the logic. However, the implementation does not build a timeline like XX days, XX minutes. I changed their code a bit:

 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 you launch it

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

The results look like this:

 = 5.37s = 11y 51d 10h 2m 16.00s 
+2
Oct 26 '18 at 10:11
source share

This function displays seconds in this format: 11h 22m, 1y 244d, 42m 4s, etc. Set the maximum variable to display as many identifiers as possible.

 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 + '; current++; } return str; } 
+1
Apr 27 '13 at 13:34
source share

To show only what you need, not day 0, clock 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; }; 
+1
Nov 29 '13 at 10:05
source share

Using Dan's answer, I came up with this, if you want to calculate the difference between the created message time (from the database you need to get it as UTC) and the user system time, and then show them the elapsed time, you can use the function below

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

for example: use

 var str = dateToStr('2014-10-05 15:22:16'); 
+1
05 Oct '14 at 16:34
source share

This is the solution. You can later divide by ":" and accept the values ​​of the array

  /** * 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); 
0
May 23 '13 at 13:36
source share

I am a big fan of objects, so I created this from https://metacpan.org/pod/Time::Seconds

Using:

 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); 
0
Mar 15 '14 at 9:59
source share

I cleaned up one of the other answers, which is a bit like 10 seconds ago style lines:

 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'; }; 
0
Mar 17 '14 at 15:20
source share

Following a similar approach to @Dan, I changed the @Royi Namir code to output a comma line and and:

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

It has no period, so you can add sentences after it, for example:

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

Where custom[0] is the total timeout; he will continue to divide the time by 2, warning about the time remaining until the end of the timer, and stop the warning when the time is less than 15 seconds.

0
Sep 24 '17 at 19:03
source share

There is an Intl.RelativeTimeFormat API, which is supported in recent versions of Chrome and Firefox.

A few examples:

 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' 

And much more in this blog post and in the offer itself .

0
Nov 13 '18 at 19:46
source share
 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}; }

-one
Nov 28 '17 at 9:23
source share



All Articles