javascript - 在倒计时中将时间从秒格式化为 HH:MM:SS
问题描述
我有这个简单的倒计时:
function offer_countdown_timer(countdown_start, countdown_time, update, complete) {
var start = new Date(countdown_start).getTime();
var interval = setInterval(function() {
var now = countdown_time-(new Date().getTime()-start);
if( now <= 0) {
clearInterval(interval);
complete();
} else {
update(Math.floor(now/1000));
}
},100); // the smaller this number, the more accurate the timer will be
}
在这里我称之为:
<script>
offer_countdown_timer(
'<%= s.created_at%>',
3600000, // 1 hour in milliseconds
function(timeleft) { // called every step to update the visible countdown
var txt = timeleft+' seconds';
$('#tender_countdown_<%= s.id %>').html(txt);
//$('#tender_countdown_<%= s.id %>').html(moment(txt).format('HH:mm:ss'));
},
function() {
$('#product_<%= s.id %>').html('Offer has expired!');
}
);
</script>
这个的输出是:
773 seconds
(它正在倒计时)
我想看到这样的东西(HH:ss:mm):
00:12:53
(并倒数)。
我尝试使用它(使用 Moment.js lib - https://momentjs.com/docs/):
$('#tender_countdown_<%= s.id %>').html(moment(txt).format('HH:mm:ss'));
但在这种情况下,输出是这样的:
01:00:00
时间信息有误,不倒计时。这是为什么?如何正确格式化倒计时时间?
谢谢
解决方案
秒数是抽象的持续时间,而不是代表特定时刻的日期。Moment 的构造函数希望您给它一个日期字符串。
Moment 有一个 Duration 对象,可以解析您的数据。它还没有很好的格式化功能,但你可以很容易地构建所需的输出:
var txt = 773;
var m = moment.duration(txt, "s");
var output = m.hours() + ":" + m.minutes() + ":" + m.seconds();
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
有关更多详细信息,请参阅https://momentjs.com/docs/#/durations/。
推荐阅读
- c# - 在创建/完成封闭类型之前如何使用嵌套类型构建器?
- azure - 将链代码部署到 Azure 上的 Hyperledger Fabric Consortium
- rest - Yii2 rest api 基本认证
- sql - ORDER BY 可能缺少列
- python - 将函数映射到 Pandas 中的列值的问题
- android - 如何合并两个菜单并对它们进行排序?
- automapper - 如何将 ExpandoObject(或动态)映射到实例上?
- qml - 自定义 Controls 2 SpinBox 时出错
- odoo - Odoo 12:向表单视图添加自定义侧边栏
- scala - MyClass 和 MyClass.this.type 之间有什么区别以及如何将其转换为另一个?