Removing 5 seconds from a variable in javascript

68 views Asked by At

I'm hoping to pull a variable from a text box that would be submitted like "201442" turn it into time 20:14:42 then subtract 5 seconds for the output 20:14:37. So far i have:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>-5</title>
<script>
var incomingtime = "0";
</script>
<script>
    function calctime(){
  incomingtime = document.getElementById("inputtime").value;
  alert (incomingtime);
    }
</script>

</head>

<body>
<input type="text" id="inputtime"/><input type="text" id="outputtime"/><br>
<button onclick="calctime()">-5 Dat</button>
</body>
</html>

What would be the best approach? Splitting up the input into three sections and doing the math that way? Or is there a simpler solution? How would i go about throwing first two chars into a variable, third and fourth into a var, then 5th and 6th into a var for calculations?

1

There are 1 answers

2
Paul  Andrusiak On

I guess, you should parse your string and put your time into Date() object, then it will be easier to do any computations on your time value You can parse it in the following way:

timeObj = new Date(0,0,0,
  incomingtime.substring(0, 2),
  incomingtime.substring(2, 4),
  incomingtime.substring(4, 6));

Then you can carry out your values, using object's 'get' functions. If you want to change its value, you can just add or substract time (in miliseconds). For example, if you want to substract 5 seconds, you should just:

timeObj -= 5*1000;