%%html

<div>
  <label for="startTime">Start Time:</label>
  <input type="time" id="startTime" placeholder="Start Time">
</div>

<div>
  <label for="endTime">End Time:</label>
  <input type="time" id="endTime" placeholder="End Time">
</div>

<button onclick="calculateTimeDifference()">Calculate Time Difference</button>

<p id="result"></p>

<script>
function calculateTimeDifference() {
  const startTime = document.getElementById('startTime').value;
  const endTime = document.getElementById('endTime').value;

  const startDate = new Date(`2000-01-01T${startTime}`);
  const endDate = new Date(`2000-01-01T${endTime}`);

  const timeDifference = Math.abs(endDate - startDate);
  const hours = Math.floor(timeDifference / (1000 * 60 * 60));
  const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));

  const resultElement = document.getElementById('result');
  resultElement.textContent = `Time difference: ${hours} hours and ${minutes} minutes`;
}
</script>

How the JavaScript Works

  • script tags
  • calculateTimeDifference() function
  • user inputs start/end times in input elements
  • times are converted into Date objects
  • time difference is calculated using the Math.abs() function
  • time difference converted into hours and minutes
  • result is stored in the resultElement variable which is shown in "result" element