## How to find duration between two time

Hello Geeks,

Today we will learn how to get duration between given two time. Some time we want to get duration of selected time period. So, how to it with help of javascript.

Here I will explain you how to do it with javascript.

Example,
We will take example of two time. Suppose we want to get sleeping duration of any person. Suppose person is sleeping at 10:00 PM and wake up at 05:00 AM. So sleeping hours is 7 and minute is 0.

Now we will do it with code.

``````
<script type="text/javascript">
function returnNumber(v) {
v = parseInt(v);
if (isNaN(v)) {
return 0;
} else {
return v;
}
}

valuestart = "10:45 PM";
valuestop = "07:30 AM";
amPM1Arr = valuestart.split(" ");
amPM2Arr = valuestop.split(" ");
amPM1 = amPM1Arr;
amPM2 = amPM2Arr;
timiningArr2 = amPM2Arr.split(":");
timiningArr1 = amPM1Arr.split(":");
if (amPM1 == amPM2) {
timiningArr2 = amPM2Arr.split(":");
timiningArr1 = amPM1Arr.split(":");
totalHour = returnNumber(timiningArr2) - returnNumber(timiningArr1);
totalMin = returnNumber(timiningArr2) - returnNumber(timiningArr1);
if (totalHour < 0 ) {
totalHour = totalMin= 0;
} else {
if(totalMin < 0) {
totalHour--;
totalMin = 60 +totalMin;
}
}
} else {
totalHour = 0;
totalMin = 0;
if (amPM1 == "PM" && amPM2 == "AM") {
totalHour += returnNumber(timiningArr2);
timiningArr1 = returnNumber(timiningArr1);
totalHour += (11 - timiningArr1);
totalMin = 60 - returnNumber(timiningArr1);
totalMin += returnNumber(timiningArr2);
} else if (amPM2 == "PM") {
totalHour = returnNumber(timiningArr2);
totalHour += (11 - timiningArr1);
totalMin = 60 - returnNumber(timiningArr1);
totalMin += returnNumber(timiningArr2);
}
if (totalMin > 60 ) {
extraH = totalMin%60;
totalHour = totalHour + extraH;
totalMin = totalMin - (extraH*60);
} else if (totalMin == 60) {
totalHour++;
totalMin=0;
}
}
console.log(totalHour+":"+totalMin);
</script>

``````