Link to home
Start Free TrialLog in
Avatar of RupertA
RupertAFlag for United Kingdom of Great Britain and Northern Ireland

asked on

subtract one time from another

Hi I am not a programmery type and was hoping somebody could help me out with a function. I have two variables, which are Bigger_Time and Smaller_Time. These variables are in the format 00:00:00. I have no idea what type of variable they are declared to because they have come from a program called lectora. So maybe it would be best in the function below to convert them to a managable form? I definitely know though that the contents of Bigger_Time and Smaller_Time is in the format 00:00:00.  So for instance 00:34:56 would mean 34 minutes and 56 seconds. I wish to be able to subtract Smaller_Time from Bigger_Time in the function below and put the result in a a variable that I have already declared called resultingtime.  For instance if Bigger_Time is 00:09:52 and Smaller_Time is 00:04:27 then the difference is 00:05:25.

I know that my function will look like this

<SCRIPT language="JavaScript">

function subtract_time()
{

IN HERE


}

</script>

I was hoping somebody could write in and show me what should go in the IN HERE part. I have had a go but have failed. Hope somebody else has the knowledge. Thanks. If you could give me the fucntion I would be grateful. If not I know I will spend hours trying to work out why it doesn't work, only for it to be something simple. Thanks.
Avatar of dsacker
dsacker
Flag of United States of America image

Complete with HTML example. :)

<html>
<head>
  <title>Time Math</title>
  <script language=javascript>
function get_time() {
    var bigger_time   = document.getElementById('bigger_time').value;
    var smaller_time  = document.getElementById('smaller_time').value;
    var resultingtime = subtract_time(bigger_time, smaller_time);
    document.getElementById('resultingtime').value = resultingtime;
}

function subtract_time(bigger_time, smaller_time) {
    var bigger_value  = convert_time_to_value(bigger_time);
    var smaller_value = convert_time_to_value(smaller_time);
    var resultingtime = convert_value_to_time(bigger_value - smaller_value)
    return resultingtime;
}

function convert_time_to_value(time_format) {
    var hh = time_format.substring(0,2);
    var mm = time_format.substring(3,5);
    var ss = time_format.substring(6,8);
    var time_value = (eval(hh) * 3600) + (eval(mm) * 60) + eval(ss);
    return time_value;
}

function convert_value_to_time(time_value) {
    var hh = Math.floor(time_value / 3600);
    var mm = Math.floor((time_value % 3600) / 60);
    var ss = Math.floor(time_value % 60);
   
    return prefix_zero(hh) + ':' + prefix_zero(mm) + ':' + prefix_zero(ss);
}

function prefix_zero(value) {
    if (value < 10)
      value = '0' + value;
    return value;
}
  </script>
</head>
<body>
<table>
  <tr>
    <td><h4>Enter Bigger Time:  </h4></td>
    <td><input type=text id=bigger_time></td>
  <tr>
  </tr>
    <td><h4>Enter Smaller Time: </h4></td>
    <td><input type=text id=smaller_time></td>
  </tr>
  <tr><td colspan=2>&nbsp;</td></tr>
  <tr>
    <td><input type=button id=calculate onclick="get_time();" value="Calculate"</td>
    <td><input type=text id=resultingtime></td>
  </tr>
</table>
</body>
</html>
All you really need are the four javascript functions: (1)  subtract_time, (2) convert_time_to_value, (3) convert_value_to_time and (4) prefix_zero.

Simply call the first function as follows:

var resultingtime = substract_time(bigger_time, smaller_time);

The subsequent functions simply do the repetitive work.
 JavaScript has a very rich Date object.  This object has the ability of processing time and date.
Since your input is only dealing with Time, you can have both times apply to Date objects for "today".

  One way to create a date object is to specify no parameters.  This will create a date object that
represents the current date and time.  For example:

  var today = new Date();

  We can then display this object value as a string using:

  var now = today.toString();

  It will have a value such as:

Tue Dec 05 2006 13:27:07 GMT-0500 (Eastern Standard Time)

  What we want to do is to use this, but to adjust the time portion using the specified values to create other Date object.
One way to do this is to separate the string into pieces, using a space/blank as the separator:

  var info = now.split( ' ' );

  The reason for doing this is so that we can discard the information after the year by adjusting the length of the array:

  info.length = 4;

  Then, we can use the join() method to build the date string that represents today:

  var today = info.join( ' ' );

  Now, we can append the specified times to this date string, and use it to create Date objects for these times:
 
  var first = new Date( today + ' ' + Smaller_Time );
  var second = new Date( today + ' ' + Bigger_Time );

  And then we can compare, and manipulate these Date objects:

  var delta = second - first;  // This is the number of milliseconds between the two values;

  Which you can how convert to hours:

  var hours = Math.floor( delta / 3600000 );    // Number of milliseconds in an hour
  delta -= hours * 3600000;                          // Remove hours from the result
  var minutes = Math.floor( delta / 60000 );   // Number of milliseconds in a minute
  delta -= minutes * 60000;                          // Remove minutes from the result
  delta /= 1000;                                           // Convert milliseconds to seconds

.....
  function timeDiff( Smaller_Time, Bigger_Time ) {
    function twoDigits( val ) {
      return ( val < 10 ) ? '0' + val : '' + val;
    }

    var today  = new Date();
    var now    = today.toString();
    var info   = now.split( ' ' );
    info.length = 4;
    var today  = info.join( ' ' );
    var first  = new Date( today + ' ' + Smaller_Time );
    var second = new Date( today + ' ' + Bigger_Time );

    var delta = second - first;  // This is the number of milliseconds between the two values;
    var hours = Math.floor( delta / 3600000 );     // Number of milliseconds in an hour
    delta -= hours * 3600000;                      // Remove hours from the result
    var minutes = Math.floor( delta / 60000 );     // Number of milliseconds in a minute
    delta -= minutes * 60000;                      // Remove minutes from the result
    delta /= 1000;                                 // Convert milliseconds to seconds
    return twoDigits( hours ) + ':' + twoDigits( minutes ) + ':' + twoDigits( delta );
  }
dsacker: I was working on this as you were posting, so I didn't see your post until after I submitted mine
Avatar of score_under
score_under

Untested, but...

<script>
smaller_time="08:20:44"; //EXAMPLE TIME
bigger_time="09:53:23";
result="00:00:00";

function pn(n){if (n<0) return 0-n; return n;}

function subtime(st,bt) // Does not matter which time is bigger, actually
{
hour_small=parseInt(st.substring(0,2));
min_small=parseInt(st.substring(3,5));
sec_small=parseInt(st.substring(6,8));
hour_big=parseInt(bt.substring(0,2));
min_big=parseInt(bt.substring(3,5));
sec_big=parseInt(bt.substring(6,8));
time_small=hour_small*3600+min_small*60+sec_small;
time_big=hour_big*3600+min_big*60+sec_big;
time_sub=pn(time_big-time_small);
hour_sub=(time_sub/3600)((time_sub/3600)%1);
min_sub=((time_sub/60)((time_sub/60)%1))%60;
sec_sub=time_sub%60
}
HonorGod: Been there (lol). No problem.

Great ID, by the way. My sentiments exactly. :)
ASKER CERTIFIED SOLUTION
Avatar of score_under
score_under

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RupertA

ASKER

Great posts guys, I went with score_under cos it looked slightly simpler. Thanks for all your help.
If you are substracting lengths of time in hours (i.e., that it takes to complete a project, etc), the last solution won't work if you have a bigger or smaller time (or both) that can exceed 24 hours in elapsed length. By using the date object to achieve this, you cannot have 24 or greater for the hour part.

If you are subtracting start and finish times by way of the clock, then it will work.