I basically want to produce the following:
from int 67 to 1 minute 7 seconds
from int 953 to 15 minutes 53 seconds
from int 3869 to 1 hour 4 minutes 29 seconds
pseudo code:
// original
<span class="time">67</span>
//output
<span class="time">1 minute 7 seconds</span>
// js
$('.time').format_duration();
Borrowing most of Guffa's answer, this should do the trick as a jQuery plugin:
jQuery.fn.time_from_seconds = function() {
return this.each(function() {
var t = parseInt($(this).text(), 10);
$(this).data('original', t);
var h = Math.floor(t / 3600);
t %= 3600;
var m = Math.floor(t / 60);
var s = Math.floor(t % 60);
$(this).text((h > 0 ? h + ' hour' + ((h > 1) ? 's ' : ' ') : '') +
(m > 0 ? m + ' minute' + ((m > 1) ? 's ' : ' ') : '') +
s + ' second' + ((s > 1) ? 's' : ''));
});
};
If you have HTML like this:
<span class='time'>67</span>
<span class='time'>953</span>
<span class='time'>3869</span>
And you call it like this:
$('.time').time_from_seconds();
The HTML is turned to:
<span class="time">1 minute 7 seconds</span>
<span class="time">15 minutes 53 seconds</span>
<span class="time">1 hour 4 minutes 29 seconds</span>
Each element also has a data attribute of 'original' with the seconds it originally contained.
My answer directly answers your question, but I'm going to take a shot in the dark: if you want to show how long ago something happened in human time (ie, "5 minutes ago") there is the jQuery timeago plugin for this. I don't think it accepts seconds as the format, though. It has to be a ISO 8601 date.
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
<script>
var tbl = [
[ 7*24*60*60, 'week' ],
[ 24*60*60, 'day' ],
[ 60*60, 'hour' ],
[ 60, 'minute' ],
[ 1, 'second' ]
];
function convert() {
var t = parseInt($('#val').val());
var r = '';
for (var i = 0; i < tbl.length; i++) {
var d = tbl[i];
if (d[0] < t) {
var u = Math.floor(t / d[0]);
t -= u * d[0];
r += u + ' ' + d[1] + (u == 1 ? ' ' : 's ');
}
}
$('#result').html(r);
}
</script>
</head>
<body>
<input id='val' type='text' size='10' />
<input type='button' value='convert' onclick='convert()' />
<div id='result' />
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With