【问题标题】:JavaScript start counting from timestampJavaScript 从时间戳开始计数
【发布时间】:2013-11-22 15:33:44
【问题描述】:

我有这个计数器,我想从特定时间戳 (1385132831.818785) 而不是 0 开始。我该怎么做?

startTimer: function(el) {      

         var counter = 0, 
         cDisplay = $(el);
         var format = function(t) {

             var minutes = Math.floor(t/600),
                 seconds = Math.floor( (t/10) % 60);
             minutes = (minutes === 0) ? "" : (minutes === 1)? minutes.toString()     + ' min ' : minutes.toString() + ' mins ';
             seconds = (seconds === 0) ? "" : seconds.toString() + ' secs';
             cDisplay.html(minutes + seconds);
         };
        setInterval(function() {
           counter++;
           format(counter);
        },100);

    }

【问题讨论】:

  • var counter = 1385132831.818785, 怎么样
  • 返回 2308555 分 10 秒
  • 你的时间戳快44岁了; )。
  • 你要显示什么
  • @Newcoma - 它真的看起来像一个有效的时间戳吗?

标签: javascript jquery datetime


【解决方案1】:

试试

var el = '.timer';
var start = 1385132831,
    cDisplay = $(el);
var format = function (t) {
    var hours = Math.floor(t / 3600),
        minutes = Math.floor(t / 60 % 60),
        seconds = Math.floor(t % 60),
        arr = [];
    if (hours > 0) {
        arr.push(hours == 1 ? '1 hr' : hours + 'hrs');
    }
    if (minutes > 0 || hours > 0) {
        arr.push(minutes > 1 ? minutes + ' mins' : minutes + ' min');
    }
    if (seconds > 0 || minutes > 0 || hours > 0) {
        arr.push(seconds > 1 ? seconds + ' secs' : seconds + ' sec');
    }
    cDisplay.html(arr.join(' '));
};
setInterval(function () {
    format(new Date().getTime() / 1000 - start);
}, 1000);

演示:Fiddle

【讨论】:

    【解决方案2】:

    我会这样做:

    $(document).ready(function () {
        var timer = {
                showTime: function (cDisplay, timestamp) {
                    var now = new Date(),
                        time = new Date(now - Math.floor(timestamp * 1000));
                    cDisplay.html(time.getUTCHours() + ' hours ' + time.getUTCMinutes() + ' mins ' + time.getUTCSeconds() + ' secs');
                    setTimeout(function () {timer.showTime(cDisplay, timestamp);}, 1000);
                }
            };
        timer.showTime($('#el'), 1385132831.818785);
    });
    

    A live demo at jsFiddle.

    【讨论】:

      猜你喜欢
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-21
      • 2017-03-05
      • 1970-01-01
      相关资源
      最近更新 更多