Solved

Calculating the difference between two user-entered times

Posted on 2003-10-21
11
391 Views
Last Modified: 2006-11-17
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
0
Comment
Question by:mremco
  • 6
  • 3
  • 2
11 Comments
 
LVL 3

Expert Comment

by:superslamwich
ID: 9595143
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}
0
 
LVL 3

Expert Comment

by:superslamwich
ID: 9595165
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)")
0
 

Author Comment

by:mremco
ID: 9595326
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?
0
 
LVL 3

Expert Comment

by:superslamwich
ID: 9595513
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}
0
 
LVL 3

Accepted Solution

by:
superslamwich earned 500 total points
ID: 9595603
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}
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 8

Expert Comment

by:inq123
ID: 9595713
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!
0
 

Author Comment

by:mremco
ID: 9595780
thanks to both superslamwich and inq123
0
 
LVL 3

Expert Comment

by:superslamwich
ID: 9602811
>>  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?
0
 
LVL 8

Expert Comment

by:inq123
ID: 9603194
 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. :-)
0
 
LVL 8

Expert Comment

by:inq123
ID: 9603237
BTW, I guess if I explained earlier about this bug maybe I would've gotten some points for my clean and correct little script. :-)
0
 
LVL 3

Expert Comment

by:superslamwich
ID: 9610528
Good call, I missed that.  You deserve these points:  

http://oldlook.experts-exchange.com/Web/Web_Languages/JavaScript/Q_20776428.html
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Avoid defining the variables in the global scope; trying to define them in a local function scope. Because:   • Look-up is performed every time a variable is accessed.   • Variables are resolved backwards from most specific to least specific scope…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now