2013-11-22 32 views
0

我有這個計數器,我想從一個特定的時間戳(1385132831.818785)開始,而不是從0開始。我該怎麼做?JavaScript從時間戳開始計數

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); 

    } 
+2

'var counter = 1385132831.818785,' – adeneo

+0

如何返回2308555分鐘10秒 – Newcoma

+0

您的時間戳將近44歲; )。 – Teemu

回答

2

嘗試

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

+0

這非常完美。謝謝 – Newcoma

1

我會做這樣的事情:

$(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