# \[php\] getTimeDifference

**URL:** <https://forum.kirupa.com/t/php-gettimedifference/221602>\
**Category:** open source\
**Created:** [April 5, 2007, 3:33pm UTC](https://forum.kirupa.com/t/php-gettimedifference/221602 "2007-04-05T15:33:38Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![icio](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/icio/32/484_2.png) [@icio](https://forum.kirupa.com/u/icio)\
**Post date:** [April 5, 2007, 3:33pm UTC](https://forum.kirupa.com/t/php-gettimedifference/221602/1 "2007-04-05T15:33:38Z")

</div>

Just a quick and dirty little function to calculate the difference in time between two times.  
Returns the number of years, weeks, days, hours, minutes and seconds between the two.

```php
function getTimeDifference($time1, $time2) {
	$dif = max($time1, $time2) - min($time1, $time2);
	return array(
		"years" => floor($dif/31536000),
		"weeks" => floor(($dif%31536000)/604800),
		"days" => floor((($dif%31536000)%604800)/86400),
		"hours" => floor(($dif%86400)/3600),
		"minutes"=> floor(($dif%3600)/60),
		"seconds"=> $dif%60,
		
		"earlier" => min($time1, $time2),
		"later" => max($time1, $time2)
	);	
}

```

Here’s a little function to format the output:

```php
function formatTimeDifference($dif) {
	$ret = "";
	$order = array("Years", "Weeks", "Days", "Hours", "Minutes", "Seconds");
	foreach($order as $part) {
		$v = $dif[strtolower($part)];
		if ($v != 0) {
			$ret .= strlen($ret) > 0 ? " " : "";
			$ret .= $v." ";
			$ret .= $v==1 ? substr($part, 0, -1) : $part;
		}
	}
	return $ret;
}

```

And here’s how you might put it into action:

```php
<?
echo "<pre>";

// First - the times
$time1 = strtotime("00:00 400 days ago");
$time2 = strtotime("today");

// Usage (doesn't matter which time is the earlier and which is the later)
$diff = getTimeDifference($time1 ,$time2);

// Output
echo "Difference between
  &middot; ".date('l dS \of F Y h:i:s A', $diff['earlier'])." and
  &middot; ".date('l dS \of F Y h:i:s A', $diff['later'])."
is:

";
print_r($diff);
echo "
".formatTimeDifference($diff);

echo "</pre>";
?>

```

Hope someone can find some use from it  
**Edit: bug fixed**
