Thursday, April 25, 2024
 Popular · Latest · Hot · Upcoming
123
rated 0 times [  129] [ 6]  / answers: 1 / hits: 120776  / 13 Years ago, mon, november 21, 2011, 12:00:00

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.


More From » datetime

 Answers
21

With help of Royi we've got code that outputs time interval in a human 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;
}

[#88988] Saturday, November 19, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gonzalo

Total Points: 336
Total Questions: 114
Total Answers: 98

Location: Iceland
Member since Sat, Sep 17, 2022
2 Years ago
;