Calculate time difference between two time fields: EDC/CDMS
Time difference between two time fields on the same day
To calculate the difference between two time fields in hours, minutes, or seconds, use the following formula:
getTimeDiff('{time_variable_2}', '{time_variable_1}', 'm');
where time_variable_1 is the first time point (time field) and time_variable_2 is the second time point. Replace these with your own variable names.
You can also change the units of time:
- For hours: use 'h' instead of 'm'
- For seconds: use 's' instead of 'm'
Since time fields capture only hours and minutes, this difference will always be rounded to the nearest 60 sec.
Note: This formula is valid only if the two times are on the same date.
Time difference between two time fields on two consecutive dates
If the two times are on two consecutive days, you can use one of the following calculations, depending on whether you want the outcome in hours, minutes, or both. This template requires the times to be filled in in a 24 hour format. This difference will be rounded to the nearest 60 sec.
Calculate the time difference in hours with:
var splitted1 = "{time1}".split(":"); var splitted2 = "{time2}".split(":"); var time1 = splitted1[0]+splitted1[1]; var time2 = splitted2[0]+splitted2[1]; time1 - time2; if (time1 < time2) { var diff = getTimeDiff('{time2}', '{time1}', 'm'); diff/60; } else { var diff1 = getTimeDiff('24:00', '{time1}', 'm'); var diff2 = getTimeDiff('{time2}', '00:00', 'm'); (diff1 + diff2)/60; };
Test this calculation in the calculation helper here.
Calculate the time difference in minutes with:
var splitted1 = "{time1}".split(":"); var splitted2 = "{time2}".split(":"); var time1 = splitted1[0]+splitted1[1]; var time2 = splitted2[0]+splitted2[1]; if (time1 < time2) { var diff = getTimeDiff('{time2}', '{time1}', 'm'); diff; } else { var diff1 = getTimeDiff('24:00', '{time1}', 'm'); var diff2 = getTimeDiff('{time2}', '00:00', 'm'); var totalDiff = diff1+diff2; totalDiff; };
Test this calculation in the calculation helper here.
Calculate the time difference in hours and minutes with:
var splitted1 = "{time1}".split(":"); var splitted2 = "{time2}".split(":"); var time1 = splitted1[0]+splitted1[1]; var time2 = splitted2[0]+splitted2[1]; var hours; var minutes; if (time1 < time2) { var diff = getTimeDiff('{time2}', '{time1}', 'm'); hours = Math.floor((diff/60)); minutes =(diff%60); } else { var diff1 = getTimeDiff('24:00', '{time1}', 'm'); var diff2 = getTimeDiff('{time2}', '00:00', 'm'); var totalDiff = diff1+diff2; hours = Math.floor((totalDiff/60)); minutes =(totalDiff%60); }; hours + " hours, " + minutes + " minutes";
Test this calculation in the calculation helper here.