在持续时间方面是否有好的jQuery插件或JS代码? [英] Is there a good jQuery plugin or JS code for time durations?
问题描述
我基本上想产生以下内容:
从int 67到1分7秒
从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();
借用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' : ''));
});
};
如果您有这样的HTML:
<span class='time'>67</span>
<span class='time'>953</span>
<span class='time'>3869</span>
您这样称呼它:
$('.time').time_from_seconds();
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>
每个元素还具有原始"的数据属性以及其最初包含的秒数.>
我的答案直接回答了您的问题,但是我将在黑暗中进行拍摄:如果您想显示人类时间多久之前(即"5分钟前")发生了什么,为此,href ="http://timeago.yarp.com/" rel ="noreferrer"> jQuery timeago插件.我不认为它接受秒作为格式.必须是 ISO 8601 日期.
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.
这篇关于在持续时间方面是否有好的jQuery插件或JS代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!