是否有一个好的jQuery插件或JS代码的持续时间?

far*_*ace 5 javascript time jquery jquery-plugins

我基本上想要产生以下内容:

从第67分钟到第1分钟7秒

从int 953到15分53秒

从int 3869到1小时4分29秒

伪代码:

// original
<span class="time">67</span>

//output
<span class="time">1 minute 7 seconds</span>

// js
$('.time').format_duration();
Run Code Online (Sandbox Code Playgroud)

Pao*_*ino 9

借用Guffa的大部分答案,这应该是jQuery插件的诀窍:

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' : ''));
    });
};
Run Code Online (Sandbox Code Playgroud)

如果您有这样的HTML:

<span class='time'>67</span>
<span class='time'>953</span>
<span class='time'>3869</span>
Run Code Online (Sandbox Code Playgroud)

你这样称呼它:

$('.time').time_from_seconds();
Run Code Online (Sandbox Code Playgroud)

HTML转向:

<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>
Run Code Online (Sandbox Code Playgroud)

每个元素还具有"原始" 的数据属性及其最初包含的秒数.

我的回答直接回答你的问题,但我会采取瞎猜:如果你想显示多久以前的东西在人体发生的时间(即,"5分钟前")存在的jQuery插件TIMEAGO此.不过,我不认为它接受秒作为格式.它必须是ISO 8601日期.


Sco*_*den 6

<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>
Run Code Online (Sandbox Code Playgroud)