我是
JavaScript的新手,我正在尝试编写一个代码,用于计算从用户登录到当前时间所经过的时间.
这是我的代码: –
function markPresent() { window.markDate = new Date(); $(document).ready(function() { $("div.absent").toggleClass("present"); }); updateClock(); } function updateClock() { var markMinutes = markDate.getMinutes(); var markSeconds = markDate.getSeconds(); var currDate = new Date(); var currMinutes = currDate.getMinutes(); var currSeconds = currDate.getSeconds(); var minutes = currMinutes - markMinutes; if(minutes < 0) { minutes += 60; } var seconds = currSeconds - markSeconds; if(seconds < 0) { seconds += 60; } if(minutes < 10) { minutes = "0" + minutes; } if(seconds < 10) { seconds = "0" + seconds; } var hours = 0; if(minutes == 59 && seconds == 59) { hours++; } if(hours < 10) { hours = "0" + hours; } var timeElapsed = hours+':'+minutes+':'+seconds; document.getElementById("timer").innerHTML = timeElapsed; setTimeout(function() {updateClock()},1000); }
输出正确到00:59:59,但之后O / P是:
0时59分59秒
1时59分59秒
1点59分00秒
1时59分01秒
.
.
.
.
1时59分59秒
01:00:00
解决方法
这里发生了太多事情.
一种更简单的方法就是每次将markDate与当前日期进行比较并重新格式化.
见演示:http://jsfiddle.net/7e4psrzu/
function markPresent() { window.markDate = new Date(); $(document).ready(function() { $("div.absent").toggleClass("present"); }); updateClock(); } function updateClock() { var currDate = new Date(); var diff = currDate - markDate; document.getElementById("timer").innerHTML = format(diff/1000); setTimeout(function() {updateClock()},1000); } function format(seconds) { var numhours = parseInt(Math.floor(((seconds % 31536000) % 86400) / 3600),10); var numminutes = parseInt(Math.floor((((seconds % 31536000) % 86400) % 3600) / 60),10); var numseconds = parseInt((((seconds % 31536000) % 86400) % 3600) % 60,10); return ((numhours<10) ? "0" + numhours : numhours) + ":" + ((numminutes<10) ? "0" + numminutes : numminutes) + ":" + ((numseconds<10) ? "0" + numseconds : numseconds); } markPresent();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div id="timer"></div>