PDA

View Full Version : calc time elapsed?

bphein1980
08-21-2005, 12:12 AM
How do you calculate time elapsed between two times?

Basically, there would be separate inputs for hours and minutes. Below is an example. I would need to find out how many hours and minutes elapsed between hour1/minute1 and hour2/minute2 and show the values in the 2 inputs below them "hoursPast/minutesPast".

<input name="hours1" /> <input name="minutes1" />
<input name="hours2" /> <input name="minutes2" />

<input name="hoursPast /> <input name="minutesPast" />

I have seen similar code that will add two times, but I was unsucessful in altering it to subtract times. I'll post the code below for the adding of times, maybe someone can go off it. Any help would be appreciated. I need bascially the same setup, but calculating just the opposite.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<title>48897</title>
<body>
<form onsubmit="makeTotal();return false;">
<table>
<tr>
<th>Minutes</th>
<th>Seconds</th>
</tr>
<tbody>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
</tbody>
</table>
<input type="submit">
</form>

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

<script type="text/javascript">
var result = document.getElementById("result");
result.style.display = "none";

function makeTotal()
{
var list = document.getElementsByTagName("form")[0].getElementsByTagName("table")[0].getElementsByTagName("input");
var total = 0;

for(var i = 0; i < list.length; i++)
{
total += (i % 2) ? Number(list[i].value) : Number(list[i].value) * 60;
}

var time = new Date(total * 1000);

result.firstChild.nodeValue = time.getUTCHours() + ":" + time.getUTCMinutes() + ":" + time.getUTCSeconds();
result.style.display = "";
}
</script>
</body>
</html>

vwphillips
08-21-2005, 08:45 PM
bit untidy but

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>

<title></title>
<script language="JavaScript" type="text/javascript">
<!--

function CalTime(obj){
ips=obj.parentNode.getElementsByTagName('INPUT');
for (zxc0=0;zxc0<4;zxc0++){
ips[zxc0].value=ips[zxc0].value.replace(/\D|\s/g,'');
}
for (zxc1=0;zxc1<4;zxc1++){
if (ips[zxc1].value==''){ return; }
}
t1=ips[0].value*60+ips[1].value*1;
t2=ips[2].value*60+ips[3].value*1;
sign='+';
if (t2<t1){ sign='-'; }
tt=Math.abs(t2-t1);
ips[4].value=sign+Math.floor(tt/60)+':'+(zxcFormat((tt)-(Math.floor((tt)/60)*60)));
}

function zxcFormat(zxcv){
if (zxcv<10){ zxcv='0'+zxcv; }
return zxcv;
}

//-->