# Get time duration between 2 dates in php

In this article, we will show you how to get the time difference between to date in PHP.
For this, you need 2 dates From date and To dates. We will create a common function,  you just need to add the from date and to date in it then it will show you the result in an array. You can use this function anywhere in your code.

### Get time duration between 2 dates in PHP

``````<?php
function timeDuration(\$from_times,\$to_times){

\$date1 = strtotime(\$from_times);
\$date2 = strtotime(\$to_times);

// Function To Get Difference between two dates
\$diff = abs(\$date2 - \$date1);

// It will give the difference year
// total seconds in a year (365*60*60*24)
\$years = floor(\$diff / (365*60*60*24));

// It will give the month, subtract it with years and
// divide the resultant date into
// total seconds in a month (30*60*60*24)
\$months = floor((\$diff - \$years * 365*60*60*24)
/ (30*60*60*24));

// To get the day, subtract it with years and
// months and divide the resultant date into
// total seconds in a days (60*60*24)
\$days = floor((\$diff - \$years * 365*60*60*24 -
\$months*30*60*60*24)/ (60*60*24));

// To get the hour, subtract it with years,
// months & seconds and divide the resultant
// date into total seconds in a hours (60*60)
\$hours = floor((\$diff - \$years * 365*60*60*24
- \$months*30*60*60*24 - \$days*60*60*24)
/ (60*60));

// To get the minutes, subtract it with years,
// months, seconds and hours and divide the
// resultant date into total seconds i.e. 60
\$minutes = floor((\$diff - \$years * 365*60*60*24
- \$months*30*60*60*24 - \$days*60*60*24
- \$hours*60*60)/ 60);

// To get the minutes, subtract it with years,
// months, seconds, hours and minutes
\$seconds = floor((\$diff - \$years * 365*60*60*24
- \$months*30*60*60*24 - \$days*60*60*24
- \$hours*60*60 - \$minutes*60));

return \$array = array(
'years'=>\$years,
'days'=>\$days,
'hours'=>\$hours,
'minutes'=>\$minutes,
'seconds'=>\$seconds,
);

}
// you can use this function where you want to show the result
\$from_times = '2018-01-23 18:16:25';
\$from_times = '2020-02-14 09:10:00';
\$result = timeDuration(\$from_times,\$to_times);
print_r(\$result);
?>``````

In our next article, we will show you the same thing in jquery