Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good jQuery plugin or JS code for time durations?

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();
like image 561
farinspace Avatar asked May 04 '09 05:05

farinspace


2 Answers

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.

like image 91
Paolo Bergantino Avatar answered Sep 22 '22 17:09

Paolo Bergantino


<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>
like image 26
Scott Evernden Avatar answered Sep 18 '22 17:09

Scott Evernden