Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Time difference calculations

Status
Not open for further replies.

humbleprogrammer

Programmer
Oct 30, 2002
315
0
0
US
Hello,

I am trying to calculate the difference between 2 times in hours/minutes. It works for the most part accept if the AM is before 1:00 AM.

For example, if I enter 12:00:00 AM for the start time and 1:30:00 AM for the end time, I get -10.-30 for the result rather than 1.30

Below is my code. Can someone help?

Code:
<script>

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 + '.' + min;
}

function timetohours()
{
var start = document.forms['frmAddTimesheet'].StartTime.value;
var end = document.forms['frmAddTimesheet'].EndTime.value;
document.forms['frmAddTimesheet'].HoursWorked.value = format_time(get_sec(end) - get_sec(start));
}
</script>


<form name='frmAddTimesheet'>
Start Time: <input type='text' name='StartTime' size='11' maxlength='11'><br>
Finish Time: <input type='text' name='EndTime' size='11' maxlength='11'>
<input type="text" onClick='timetohours(this.form)' name="HoursWorked" value="<%=HoursWorked%>" size="4" />
</form>

 

If you create date objects from your input times (both with the same date, but different times), and then use the "getTime()" method to convert the times to milliseconds, then it becomes a simple case of subtracting start from end, and dividing the result by 1000 to get number of seconds. From that, getting minutes and seconds should be a doddle.

Hope this helps,
Dan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top