最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there a good jQuery plugin or JS code for time durations? - Stack Overflow

programmeradmin2浏览0评论

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();

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();
Share Improve this question edited May 4, 2009 at 5:25 farinspace asked May 4, 2009 at 5:08 farinspacefarinspace 8,8016 gold badges35 silver badges48 bronze badges 3
  • I think this is more of a JavaScript question than a jQuery question. What you're asking for really falls out of the scope of what jQuery is for... – Zack The Human Commented May 4, 2009 at 5:24
  • You are probably right, but figured I would make it jquery related in the case of an available plugin ... I'm starting to code something now, but im sure this code is available somewhere ... – farinspace Commented May 4, 2009 at 5:27
  • Actually, if I remember there was a blog post about hoe SO generates its timestamps in a "human-friendly" way... I thought there was some source code that would be useful there but I can't seem to find it now. – Zack The Human Commented May 4, 2009 at 5:33
Add a comment  | 

7 Answers 7

Reset to default 9

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>

Give the element an id so that it's easy to access:

<span id="time">67</span>

Now you can get the value and convert it:

var o = document.getElementById('time');
var t = parseInt(o.innerHTML);
var h = Math.floor(t / 3600);
t %= 3600;
var m = Math.floor(t / 60);
var s = t % 60;
o.innerHTML =
   (h > 0 ? h + ' hours ' : '') +
   (m > 0 ? m + ' minutes ' : '') +
   s + ' seconds';

Edit:
Added Math.floor() as suggested by Mike B.

Just in case you're looking for something more concise, and want to avoid the trailing whitespace and incorrect pluralization issues of some of the other attempts:

function timeString( t ) {
    var ret = [], t = {
        hour: parseInt(t/3600),
        minute: parseInt(t/60%60),
        second: t%60
    };

    for ( var n in t )
        t[n] && ret.push( t[n], n + "s".substr( t[n] < 2 ) );

    return ret.join(" ");
}

It's not elegant, but should work:

function format_duration(elem) {
var num = parseInt($(elem).text());
var hours = 0;
var mins = 0;
var secs = 0;
while (num > 0) {
  if (num < 60) {
    secs += num;
    num = 0;
  }
  else if (num < 3600) {
    mins++;
    num -= 60;
  }
  else if (num < 86400) {
    hours++;
    num -= 3600;
  }
}
var rv = "";
if (hours > 0) {
    rv += hours+" hours ";
}
if (mins > 0) {
    rv += mins+" mins ";
}
if (secs > 0) { 
    rv += secs+" secs ";
}
$(elem).text(rv);
}

(updated to answer jquery usage too)

Use setTimeOut(expression,milisecs)

where expression can be the function to be called when the time in milisecs is completed.

A good example manipulating several time counters can be found at: http://www.plus2net.com/javascript_tutorial/timer-set.php

nice Guffa. You'll need to add some "floor" calls in there, though:

<snip>
    var h = Math.floor(t / 3600);
    t %= 3600;
    var m = Math.floor(t / 60);
<snip>
发布评论

评论列表(0)

  1. 暂无评论