Skip to content

Instantly share code, notes, and snippets.

@PatricNox
Last active January 16, 2020 09:57
Show Gist options
  • Save PatricNox/b81c7bf31cd83dd6813961516a53b28c to your computer and use it in GitHub Desktop.
Save PatricNox/b81c7bf31cd83dd6813961516a53b28c to your computer and use it in GitHub Desktop.
Calculate the difference between two html time field types
<!-- HTML fields -->
<input type="time" class="field--time-period-from">
<input type="time" class="field--time-period-to">
<input type="text" class="field--time-difference" disabled>
<script>
// Get the inputs.
let timeField = document.querySelector('.field--time-difference');
let from = document.querySelector('.field--time-period-from').value;
let to = document.querySelector('.field--time-period-to').value;
// Get the time in minutes.
let time_1 = parseInt(from.split(':')[0]) * 60 + parseInt(from.split(':')[1]);
let time_2 = parseInt(to.split(':')[0]) * 60 + parseInt(to.split(':')[1]);
// Find the time field and update its value to the time diff.
let timeField = document.querySelector('.field--time-amount');
timeField.value = (parseFloat(time_2 - time_1) / 60) + 'h';
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment