JavaScript从时间戳开始计数

JavaScript start counting from timestamp

本文关键字:开始 时间戳 JavaScript      更新时间:2023-09-26

我有一个计数器,我想从一个特定的时间戳(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 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

我会这样做:

$(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);
});

jsFiddle的现场演示。