# Calculating the difference between two user-entered times

Hi -

I have a form where the user enters a Start Time and a Finish Time in the following format: (HH:MM:SS AM/PM); and  I need to be able to calculate the difference between the two times using JavaScript.

ie...
Start Time:   11:00:00 AM
Finish Time:  01:00:00 PM

My thinking was that the two values would need to be converted to military, ie 24 hr, time before the calculations could take place.  I am at a loss at how to best do that operation and would greatly appreciate any insight.

Thanks -

Mike
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
Try this:

<script type='text/javascript'>
<!--

function calculateDif(frm)  {
shour = frm.shour.value*1
smin = frm.smin.value*1
ssec = frm.ssec.value*1
fhour = frm.fhour.value*1
fmin = frm.fmin.value*1
fsec = frm.fsec.value*1

if(frm.sampm.options[frm.sampm.selectedIndex].value == 'PM')  shour += 12
if(frm.fampm.options[frm.fampm.selectedIndex].value == 'PM')  fhour += 12

stime = shour * 3600 + smin * 60 + ssec
ftime = fhour * 3600 + fmin * 60 + fsec

dtime = ftime - stime
dhour = Math.floor(dtime/3600)
dtime -= dhour * 3600
dmin = Math.floor(dtime/60)
dtime -= dmin * 60
dsec = dtime

alert("The difference is:\n\n" + dhour + "hour, " + dmin + "minutes, and " + dsec + "second(s)")
}

//-->
</script>

<form name='frm'>
Start Time(HH,MM,SS):<input type='text' name='shour' size='1' maxlength='2'><input type='text' name='smin' size='2' maxlength='2'><input type='text' name='ssec' size='2' maxlength='2'><select name='sampm'><option value='AM'>AM</option><option value='PM'>PM</option></select><br>
Finish Time(HH,MM,SS):<input type='text' name='fhour' size='2' maxlength='2'><input type='text' name='fmin' size='2' maxlength='2'><input type='text' name='fsec' size='2' maxlength='2'><select name='fampm'><option value='AM'>AM</option><option value='PM'>PM</option></select><br>
<input type='button' value='Calculate Difference!' onClick='calculateDif(this.form)'>
</form>

{Slam}
Commented:
Whoops, alert should be (just so it looks good):

alert("The difference is:\n\n" + dhour + " hour(s), " + dmin + " minute(s), and " + dsec + " second(s)")
Author Commented:
thanks superslamwich,

looks like it should work, but is there anyway to do it where the user enters all information in just ONE text box?
Commented:
No problem.  Here you go.  This script also checks to make sure the time is entered in an acceptable format and alerts the user if it isn't:

<script type='text/javascript'>
<!--

function calculateDif(frm)  {
re = /^(\d{1,2}):(\d{2}):(\d{2})\s((AM)|(PM))\$/
if(!re.test(frm.stime.value))  {
alert("You need to change your start time to the format:\n\nHH:MM:SS (AM or PM)")
frm.stime.focus()
return false;
} else {
shour = RegExp.\$1*1
smin = RegExp.\$2*1
ssec = RegExp.\$3*1
sampm = RegExp.\$4
}

if(!re.test(frm.ftime.value))  {
alert("You need to change your finish time to the format:\n\nHH:MM:SS (AM or PM)")
frm.ftime.focus()
return false;
} else {
fhour = RegExp.\$1*1
fmin = RegExp.\$2*1
fsec = RegExp.\$3*1
fampm = RegExp.\$4
}

if(sampm=="PM")  shour += 12
if(fampm=="PM")  fhour += 12

stime = shour * 3600 + smin * 60 + ssec
ftime = fhour * 3600 + fmin * 60 + fsec

dtime = ftime - stime
dhour = Math.floor(dtime/3600)
dtime -= dhour * 3600
dmin = Math.floor(dtime/60)
dtime -= dmin * 60
dsec = dtime

alert("The difference is:\n\n" + dhour + " hour(s), " + dmin + " minute(s), and " + dsec + " second(s)")
}

//-->
</script>

<form name='frm'>
Start Time(HH:MM:SS (AM or PM)):<input type='text' name='stime' size='11' maxlength='11'><br>
Finish Time(HH,MM,SS (AM or PM)):<input type='text' name='ftime' size='11' maxlength='11'><br>
<input type='button' value='Calculate Difference!' onClick='calculateDif(this.form)'>
</form>

{Slam}
Commented:
Here's better validation, and this one will allow you to pass more than 12 hours (i.e. going from 2:00:00 AM to 1:00:00 AM) and will accept am, Am, aM, and AM instead of just AM (ditto for PM)

<script type='text/javascript'>
<!--

function calculateDif(frm)  {
re = /^(\d{1,2}):(\d{2}):(\d{2})\s((AM)|(PM))\$/i
if(!re.test(frm.stime.value))  {
alert("You need to change your start time to the format:\n\nHH:MM:SS (AM or PM)")
frm.stime.focus()
return false;
} else {
shour = RegExp.\$1*1
smin = RegExp.\$2*1
ssec = RegExp.\$3*1
sampm = RegExp.\$4
if(shour < 1 || shour > 12)  {
alert("Too many/few hours in your start time");
frm.stime.focus();
return false;
}
if(smin > 59)  {
alert("Too many minutes in your start time");
frm.stime.focus();
return false;
}
if(ssec > 59)  {
alert("Too many seconds in your start time");
frm.stime.focus();
return false;}
}

if(!re.test(frm.ftime.value))  {
alert("You need to change your finish time to the format:\n\nHH:MM:SS (AM or PM)")
frm.ftime.focus()
return false;
} else {
fhour = RegExp.\$1*1
fmin = RegExp.\$2*1
fsec = RegExp.\$3*1
fampm = RegExp.\$4
if(fhour < 1 || fhour > 12)  {
alert("Too many/few hours in your finish time");
frm.ftime.focus();
return false;
}
if(fmin > 59)  {
alert("Too many minutes in your finish time");
frm.ftime.focus();
return false;
}
if(fsec > 59)  {
alert("Too many seconds in your finish time");
frm.ftime.focus();
return false;
}
}

if(sampm=="PM")  shour += 12
if(fampm=="PM")  fhour += 12

stime = shour * 3600 + smin * 60 + ssec
ftime = fhour * 3600 + fmin * 60 + fsec

dtime = ftime - stime
if(dtime < 1)  dtime += (24*3600)
dhour = Math.floor(dtime/3600)
dtime -= dhour * 3600
dmin = Math.floor(dtime/60)
dtime -= dmin * 60
dsec = dtime

alert("The difference is:\n\n" + dhour + " hour(s), " + dmin + " minute(s), and " + dsec + " second(s)")
}

//-->
</script>

<form name='frm'>
Start Time(HH:MM:SS (AM or PM)):<input type='text' name='stime' size='11' maxlength='11'><br>
Finish Time(HH,MM,SS (AM or PM)):<input type='text' name='ftime' size='11' maxlength='11'><br>
<input type='button' value='Calculate Difference!' onClick='calculateDif(this.form)'>
</form>

{Slam}

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Commented:
Hi mremco,

I didn't have time earlier but did finish a version.  While superslamwich's deal with validation and provides a form, my version does not suffer a bug in his code and is somewhat cleaner:

<script>

var start = '11:00:00 AM';
var end = '12:59:59 PM';
alert("difference is " + format_time(get_sec(end) - get_sec(start)));

function get_sec(time)
{
regextest = /^(\d+):(\d+):(\d+)\s+(\w)M\$/i.test(time);
with (RegExp)
{
var sec = +\$1 * 3600 + +\$2 * 60 + +\$3;
if(\$4 == 'A' || \$4 == 'a')
return sec;
else
return (1 - parseInt(\$1 / 12)) * 12 * 3600 + sec;
}
}

function format_time(sec)
{
var hour = parseInt(sec / 3600);
var min = parseInt((sec - hour * 3600) / 60);
var sec1 = sec - hour * 3600 - min * 60;
return hour + ' hours ' + min + ' minutes ' + sec1 + ' seconds';
}

</script>

Cheers!
Author Commented:
thanks to both superslamwich and inq123
Commented:
>>  While superslamwich's deal with validation and provides a form, my version does not suffer a bug in his code and is somewhat cleaner

What bug?
Commented:
if(sampm=="PM")  shour += 12
if(fampm=="PM")  fhour += 12

Note that I deliberately use '12:59:59 PM' in my program to showthat your program would not deal with it correctly since for 12 PM, you shouldn't add 12.  You can see my way of dealing with it using one statement.

Sadly I didn't get a single point. :-)
Commented:
BTW, I guess if I explained earlier about this bug maybe I would've gotten some points for my clean and correct little script. :-)
Commented:
Good call, I missed that.  You deserve these points:

http://oldlook.experts-exchange.com/Web/Web_Languages/JavaScript/Q_20776428.html
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.