## 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[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>

``````

## Duration between two dates and time

Hello, Today we are going to code how to get duration between two dates and time in PHP.

1. Duration between two dates.

Suppose we have two dates. Two get duration between two dates, we first need to convert date in to time stamp using function strtotime. then we will minus one date from another date.

Example :

\$date1 = “01/01/2018”;

\$date2 = “17/01/2018”;

\$date1 = strtotime(\$date1);

\$date2 = strtotime(\$date2);

\$dateDiff = \$date2 – \$date1;

\$duration = floor(\$dateDiff / (60 * 60 * 24));

2. Duration between two times.

Suppose we have two times. Two get duration between two times, we first need to convert time in to time stamp using function strtotime. then we will minus one time from another time.

Example :

\$time1 = “13:00”;

\$time2 = “17:00”;

\$time1 = strtotime(date(“Y-m-d”) . ” ” . \$time1);

\$time2 = strtotime(date(“Y-m-d”) . ” ” . \$time2);

\$duration =  round(abs(\$time2 – \$time1) / 60, 2);