How to get difference of two datetime values in PHP

Sometimes we have to calculate the age of a member or the number of days since the member has logged into the system. This can easily be done in mySQL by using the datediff function however it’s always a good idea to know other ways to calculate the difference and today we are going to do just that in PHP. The following function will return the difference in number of days between two date time values passed to it. You also have the option to return any other value such as month, hour etc.

function diff_time($datetime1, $datetime2) {
	$diff = strtotime($datetime2) - strtotime($datetime1);
	$years = floor($diff / (365*60*60*24));
	$months = floor($diff / (30*60*60*24));
	$days = floor($diff / (60*60*24));
	$hours = floor($diff / (60*60));    
	$minutes  = floor($diff / 60);
	$seconds = $diff;   	
	return $days;
// Passing in two dates
echo "Number of days = ". diff_time('1980-01-01 11:30:45','2013-04-04 11:45:00');

Be the first to comment

Leave a Reply