title: JavaScript/jQuery: Subtract hours and minutes
body: <h1>What I have:</h1>
  
  <p>Three time inputs consisting of a start time, end time and the difference between the two.</p>
  
  <pre><code>&lt;input type="time" name="starttime" id="starttime"&gt;
  &lt;input type="time" name="endtime" id="endtime"&gt;
  &lt;input type="time" name="duration" id="duration" disabled&gt;
  </code></pre>
  
  <h1>What I need:</h1>
  
  <p>When the start or end time changes, the difference shows in the third input.</p>
  
  <p>e.g. 23:15 - 20:00 = 03:15.</p>
  
  <h1>What I've tried:</h1>
  
  <p>So far, I can only produce the correct hours but not the minutes.</p>
  
  <pre><code>&lt;script&gt;
      jQuery(document).ready(function($) {
  
          function calculateTime() {
  
          // Get values.
          var valuestart = $("#starttime").val();
          var valuestop = $("#endtime").val();
  
          // Create date format.          
          var timeStart = new Date("01/01/2007 " + valuestart);
          var timeEnd = new Date("01/01/2007 " + valuestop);
  
          // Subtract.
          var difference = timeEnd - timeStart;             
  
          // Attempt 1: Only gets hours.
          //var difference_as_hours = difference / 60 / 60 / 1000;
          //alert("Hour Difference: " + difference_as_hours); 
  
          // Attempt 2: Nothing happens.
          //var difference_as_hours_and_minutes = difference.getHours() + ":" + difference.getMinutes(); 
          //alert("Hour And Minutes Difference: " + difference_as_hours_and_minutes); 
  
          // Attempt 3: Nothing happens.
          //var difference_as_date = new Date("01/01/2007 " + difference);
          //var difference_as_hours_and_minutes = difference_as_date.getHours() + ":" + difference_as_date.getMinutes(); 
          //alert("Hour And Minutes Difference: " + difference_as_hours_minutes); 
  
          // Attempt 4: Nothing happens.
          var formatted_time = time_format(difference);
          alert(formatted_time);
  
  
          }
          $("#starttime, #endtime").change(calculateTime);
          calculateTime();
  
  
      });
  
  
      function time_format(d) {
          hours = format_two_digits(d.getHours());
          minutes = format_two_digits(d.getMinutes());
          seconds = format_two_digits(d.getSeconds());
          return hours + ":" + minutes + ":" + seconds;
      }
  
      function format_two_digits(n) {
          return n &lt; 10 ? "0" + n : n;
      }
  
  
  &lt;/script&gt;
  </code></pre>
  
  <p>How can I produce the hours and minutes?</p>