solve negative values in a javascript based countdown
I am creating a countdown to count the time between a开发者_运维知识库 match of the euro2012 that I intend to watch. I've come with a working version of it but I don't understand why it gives me sometimes negative values. I think it has to do with the way I wrote it, using the getTime() method. Here is my code, could you guys help me find out to solve those negative values? Thank you very much in advance.
<body onload="timeto2012()">
<script type="text/javascript">
function timeto2012() {
var euro2012 = new Date(2012, 5, 10, 20, 45);
var euro2012ms = euro2012.getTime();
var now = new Date();
var nowms = now.getTime();
var diff = euro2012ms - nowms;
var seconds = 1000;
var minutes = seconds*60;
var hours = minutes*60;
var days = hours*24;
var years = days*365;
var ddays = diff/days;
var dhours = (ddays - Math.round(ddays,1))*24;
var dminutes = (dhours - Math.round(dhours))*60;
var dseconds = (dminutes - Math.round(dminutes))*60;
document.getElementById("time").innerHTML='' + Math.round(ddays,1) +' days '+ Math.round(dhours,1) +' hours '+ Math.round(dminutes,1) +' minutes '+ Math.round(dseconds,1) + ' seconds remaining';
}
t=setInterval(timeto2012,500);
</script>
<div id="time"></div>
</body>
KOGI has the answer to your problem: You should use Math.floor
instead of Math.round
:
When there's x minutes and 30 - 59 seconds left, the (x - Math.round(x))
would be equivalent to (x - (x + 1))
after the rounding was done.
var ddays = diff/days;
var dhours = (ddays - Math.floor(ddays))*24;
var dminutes = (dhours - Math.floor(dhours))*60;
var dseconds = (dminutes - Math.floor(dminutes))*60;
Fiddle: http://jsfiddle.net/YHktx/3/
Here are some better calculations for you (derived from Aleksi Yrttiaho's jsFiddle)
var seconds = 1000;
var minutes = seconds*60;
var hours = minutes*60;
var days = hours*24;
var years = days*365;
var ddays = Math.floor( diff/days );
var dhours = Math.floor((diff % days) / hours );
var dminutes = Math.floor(((diff % days) % hours) / minutes );
var dseconds = Math.floor((((diff % days) % hours) % minutes) / seconds );
精彩评论