我有这个计数器,我想从一个特定的时间戳(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);
}
答案 0 :(得分:3)
尝试
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
答案 1 :(得分: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);
});