Jump to content

time elapsed doesn't work properly


pamporo

Recommended Posts

Hello guys! I am trying to write a simple clock counter that given a fixed date, will count the time elapsed from that moment on. I wrote the following code that works except for a bug: if the fixed date ('pastDate' in the code) is greater than today, the code calculates a countdown instead of the time elapsed, otherwise it works smoothly. f.e. with the code below, notice the number of days. Try to set 'pastDate' to anything before today instead. Does anyone know why or have suggestions on how to fix it? Thanks and happy holidays!!

<!DOCTYPE html><html>    <head>	    <meta charset="utf-8">	    <title>Counter</title>    <script>	  var int=self.setInterval(function(){	    clock()},1000	  );	  var pastDate = new Date("December 28, 2011 00:00:00")	  function clock() {	    var d=new Date();	    var months = d.getMonth() - pastDate.getMonth();	    var years = d.getFullYear() - pastDate.getFullYear();	    var days = d.getDate() - pastDate.getDate();	    var hours = d.getHours() - pastDate.getHours();	    var minutes = d.getMinutes() - pastDate.getMinutes();	    var seconds = d.getSeconds() - pastDate.getSeconds();	    //var t=diff.toLocaleTimeString();	    document.getElementById("counter").innerHTML=years + " : " + months + " : " + days + " : " + hours + " : " + minutes + " : " + seconds;	  }    </script>    </head>    <body>	    <span id="counter" style="border: solid red 1px; color: yellow; background-color:#000000;">Hello World</span>    </body></html>

Link to comment
Share on other sites

You should save the start time as a unix timestamp (using getTime()), then subtract that from the current time to know the amount of milliseconds that have passed between the two dates. With the resulting number you can use divisions and remainders to determine the days, hours, minutes and seconds.

Link to comment
Share on other sites

The problem with your approach is that subtracting is going to give wrong results. If the current month is 0 and the previous month is 11, it's going to tell you that -11 months have passed. If the current hour is 3 and the past time was 20 then it's going to tell you that -17 hours have passed. The same with minutes, seconds, milliseconds and all other units. Simply subtracting the units of time separately is going to result in really inaccurate values.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...