首页 > 解决方案 > 在倒计时中将时间从秒格式化为 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

时间信息有误,不倒计时。这是为什么?如何正确格式化倒计时时间?

谢谢

标签: javascriptmomentjs

解决方案


秒数是抽象的持续时间,而不是代表特定时刻的日期。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/


推荐阅读