Time difference

Calculate the difference between two times
This form illustrates how to calculate a time difference between two time values. It is also shown how this can be implemented in a repeating container.
Time span and computed difference

// (Help function) Calculation of the diffrence between the time values

function calcDiffrence($timeFields) {

var timeFrom = getDateVal($timeFields.get(0));

var timeUntil = getDateVal($timeFields.get(1));

if(!timeFrom || !timeUntil) return 0;

let diffInMilliSeconds = Math.abs(timeUntil - timeFrom) / 1000;

// calculate hours

const hours = Math.floor(diffInMilliSeconds / 3600) % 24;

diffInMilliSeconds -= hours * 3600;

// calculate minutes

const minutes = Math.floor(diffInMilliSeconds / 60) % 60;

diffInMilliSeconds -= minutes * 60;

return hours+':'+('0' + minutes).slice(-2);

}

// (Help-function) Convert time information into date format

function getDateVal(el){

var splittedTime = $(el).val().split(':');

if (splittedTime.length != 2) return false;

var date = new Date();

date.setHours(splittedTime[0]);

date.setMinutes(splittedTime[1]);

return date;

}

// jQuery function to set the result on the corresponding field

$.fn.setResult = function($timeFields) {

var result = calcDiffrence($timeFields);

$(this).val(result);

}

// Object of the two input fields

var $timeFields = $('[data-name="tfTimeFrom"],[data-name="tfTimeUntil"]');

// The difference is calculated for every change

$timeFields.on('change', function() {

$('[data-name="tfTimeDiffrence"]').setResult($timeFields);

}).trigger('change');

Time span and computed difference with repeated elements

// Object of the two input fields from the repeating container

var $timeFieldsDyn = $('[data-org-name="tfTimeFromDyn"],[data-org-name="tfTimeUntilDyn"]');

// The help functions can be found in the example above.

// Set initial calcuation on the first row.

$timeFieldsDyn.on('change', function() {

$('[data-org-name="tfTimeDiffrenceDyn"]').setResult($timeFieldsDyn);

}).trigger('change');

// Applying the calculation to the new added repeating fields

$('[data-name="divDyn"]').dynamic('option', 'afterAdd', function(_, row) {

var $timeFrom = row.find('[data-org-name="tfTimeFromDyn"]');

var $timeUntil = row.find('[data-org-name="tfTimeUntilDyn"]');

var $timeFields = $timeFrom.add($timeUntil);

var setResultDyn = function() {

var $timeDiff = row.find('[data-org-name="tfTimeDiffrenceDyn"]');

$timeDiff.setResult($timeFields);

};

$timeFields.on('change', setResultDyn).trigger('change');

});