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[1];
amPM2 = amPM2Arr[1];
timiningArr2 = amPM2Arr[0].split(":");
timiningArr1 = amPM1Arr[0].split(":");
if (amPM1 == amPM2) {
timiningArr2 = amPM2Arr[0].split(":");
timiningArr1 = amPM1Arr[0].split(":");
totalHour = returnNumber(timiningArr2[0]) - returnNumber(timiningArr1[0]);
totalMin = returnNumber(timiningArr2[1]) - returnNumber(timiningArr1[1]);
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[0]);
timiningArr1[0] = returnNumber(timiningArr1[0]);
totalHour += (11 - timiningArr1[0]);
totalMin = 60 - returnNumber(timiningArr1[1]);
totalMin += returnNumber(timiningArr2[1]);
} else if (amPM2 == "PM") {
totalHour = returnNumber(timiningArr2[0]);
totalHour += (11 - timiningArr1[0]);
totalMin = 60 - returnNumber(timiningArr1[1]);
totalMin += returnNumber(timiningArr2[1]);
}
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>
```