title: Calculating the time difference in an PHP/MySQL/JavaScript system
body: <p>I was wondering what the best way is to calculate the difference in time from now to a certain point, let's say the countdown time.</p>
  
  <p>I have an auction that has a closetime at a certain point, this time is stored in a MySQL record in the format " DATETIME 00-00-000 00:00:00 ". This record is called closetime.</p>
  
  <p>Now on my website I have JavaScript code that gets this time via a PHP file. The JavaScript loops every second using <code>setInterval 1000</code>. The PHP file gets the closetime from the db, and sends it back in this format</p>
  
  <pre><code>strtotime($result['closetime']);
  </code></pre>
  
  <p>And I get the time of the request, I want to use the server time, and not the time in JavaScript, because the clock of the user can be off.</p>
  
  <pre><code>strtotime(date("H:i:s", $_SERVER['REQUEST_TIME']))
  </code></pre>
  
  <p>I send back these two timestamps and calculate the time difference between them in JavaScript. I use this function to do it, the values send back from PHP I call currentTime and closeTime, I think this should be clear.</p>
  
  <pre><code>function auctionDelayTime(currentTime,closeTime){
      totaldelay = closeTime - currentTime;
      if(totaldelay &lt;= 0){
          return 'ended';
      }else{
          if( days=parseInt((Math.floor(totaldelay/86400))) )
              totaldelay = totaldelay % 86400;
          if( hours=parseInt((Math.floor(totaldelay/3600))) )
              totaldelay = totaldelay % 3600;
        if( minutes=parseInt((Math.floor(totaldelay/60))) )
              totaldelay = totaldelay % 60;
          if( seconds=parseInt((Math.floor(totaldelay/1))) )
              totaldelay = totaldelay % 1;
  
          return hours+':'+formatTimes(minutes)+':'+formatTimes(seconds);
      }
  }
  function formatTimes(value){
      return value &lt; 10 ? '0'+value : value;
  }
  </code></pre>
  
  <p>I think this is an awful lot of code do something so simple. Does anyone have a better solution or maybe more 'beautiful' code.</p>
  
  <p>Enjoy!</p>