MaDmiX

Sep 20th, 2012, 05:03 PM

Hi All,

I wrote a simple function to calculate the difference between two times within a 24 hour period.

function calculateTime(time1,time2) {

var hours1 = parseInt(time1.slice(0,2),10);

var mins1 = parseInt(time1.slice(3,5),10);

var secs1 = parseInt(time1.slice(6,8),10);

var hours2 = parseInt(time2.slice(0,2),10);

var mins2 = parseInt(time2.slice(3,5),10);

var secs2 = parseInt(time2.slice(6,8),10);

if (hours1>hours2) {

hours2=hours2+24;

}

var startTime = (hours1 * 3600) + (mins1 * 60) + (secs1);

var endTime = (hours2 * 3600) + (mins2 * 60) + (secs2);

var totalSecs = endTime-startTime;

var sumHours = parseInt(totalSecs / 3600, 10);

var sumMins = parseInt((totalSecs - sumHours * 3600) / 60, 10);

var sumSecs = totalSecs - sumHours * 3600 - sumMins * 60;

var i;

var sumTime = Array();

sumTime[0] = sumHours;

sumTime[1] = sumMins;

sumTime[2] = sumSecs;

for (i=0;i<sumTime.length;i++) {

if(sumTime[i] < 10) {

sumTime[i] = "0" + sumTime[i];

}

}

return sumTime.join(':');

}

This works great but I can't figure out how to call the function. I want to create a table where users will enter their start and end times into text boxes in a <tr> and have the result displayed in a cell on the same row.

Any ideas? This one seems simple but I seem to be at a loss. I thought about using window.onLoad but not sure that's the best (if even possible) approach.

Thanks in advance for you guidance here.

Kind regards,

Ken

I wrote a simple function to calculate the difference between two times within a 24 hour period.

function calculateTime(time1,time2) {

var hours1 = parseInt(time1.slice(0,2),10);

var mins1 = parseInt(time1.slice(3,5),10);

var secs1 = parseInt(time1.slice(6,8),10);

var hours2 = parseInt(time2.slice(0,2),10);

var mins2 = parseInt(time2.slice(3,5),10);

var secs2 = parseInt(time2.slice(6,8),10);

if (hours1>hours2) {

hours2=hours2+24;

}

var startTime = (hours1 * 3600) + (mins1 * 60) + (secs1);

var endTime = (hours2 * 3600) + (mins2 * 60) + (secs2);

var totalSecs = endTime-startTime;

var sumHours = parseInt(totalSecs / 3600, 10);

var sumMins = parseInt((totalSecs - sumHours * 3600) / 60, 10);

var sumSecs = totalSecs - sumHours * 3600 - sumMins * 60;

var i;

var sumTime = Array();

sumTime[0] = sumHours;

sumTime[1] = sumMins;

sumTime[2] = sumSecs;

for (i=0;i<sumTime.length;i++) {

if(sumTime[i] < 10) {

sumTime[i] = "0" + sumTime[i];

}

}

return sumTime.join(':');

}

This works great but I can't figure out how to call the function. I want to create a table where users will enter their start and end times into text boxes in a <tr> and have the result displayed in a cell on the same row.

Any ideas? This one seems simple but I seem to be at a loss. I thought about using window.onLoad but not sure that's the best (if even possible) approach.

Thanks in advance for you guidance here.

Kind regards,

Ken