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:
JavaScript
x
7
1
34 seconds
2
12 minutes
3
4 hours
4
5 days
5
4 months
6
1 year
7
No formatting required, hard-coded format will go.
Advertisement
Answer
With help of Royi we’ve got code that outputs time interval in a human readable form:
JavaScript
1
33
33
1
function millisecondsToStr (milliseconds) {
2
// TIP: to find current time in milliseconds, use:
3
// var current_time_milliseconds = new Date().getTime();
4
5
function numberEnding (number) {
6
return (number > 1) ? 's' : '';
7
}
8
9
var temp = Math.floor(milliseconds / 1000);
10
var years = Math.floor(temp / 31536000);
11
if (years) {
12
return years + ' year' + numberEnding(years);
13
}
14
//TODO: Months! Maybe weeks?
15
var days = Math.floor((temp %= 31536000) / 86400);
16
if (days) {
17
return days + ' day' + numberEnding(days);
18
}
19
var hours = Math.floor((temp %= 86400) / 3600);
20
if (hours) {
21
return hours + ' hour' + numberEnding(hours);
22
}
23
var minutes = Math.floor((temp %= 3600) / 60);
24
if (minutes) {
25
return minutes + ' minute' + numberEnding(minutes);
26
}
27
var seconds = temp % 60;
28
if (seconds) {
29
return seconds + ' second' + numberEnding(seconds);
30
}
31
return 'less than a second'; //'just now' //or other string you like;
32
}
33