Hsan Hsan - 1 month ago 18
Javascript Question

Display time calculation in full format

I have a small time calculator which subtracts the number of minutes from a 24 hour time e.g. 22 minutes taken from 13:30 equals 13:08, however, instead of displaying "13:08" my webpage displays "13:8" is there anyway to make it display the "13:08"?

Javascript:

function myFunction() {

function converToMinutes(s) {
var c = s.split(':');
return parseInt(c[0]) * 60 + parseInt(c[1]);
}

function parseTime(s) {
return Math.floor(parseInt(s) / 60) + ":" + parseInt(s) % 60
}


var endTime = document.getElementById("etime").value;
var startTime = converToMinutes(document.getElementById("stime").value);
var converted = parseTime(startTime - endTime);


document.getElementById('finishtime').innerHTML = converted;

}


HTML:

<p>Please enter minutes</p>
<input type="text" id="etime">
<br>
<p>Please enter time in 24 hour format (eg. 15:00)</p>
<input type="text" id="stime">
<br>
<br>
<button onclick="myFunction()">Try it</button>

<p id="finishtime">

Answer

Replace

return Math.floor(parseInt(s) / 60) + ":" + parseInt(s) % 60;

with

var seconds = parseInt(s) % 60;
return Math.floor(parseInt(s) / 60) + ":" + ((seconds < 10)?"0"+seconds:seconds);