Calculate time difference between dates
By: Daniel
Do you need to calculate the difference between two different dates? The following code can be used to calculate a users age or find how long ago project was started/completed.
function timeDifference($oldtime) { $time = time(); // Get the unix timestamp for today $elapsed = $time - $oldtime; // How many seconds between today and the date in question $years = date('Y', $elapsed) - 1970; // Calculate the year subtracting the beginning year 1970 $months = date('n', $elapsed); // Calculate months $days = date('j', $elapsed); // Calculate days return array('years'=>$years, 'months'=>$months, 'days'=>$days); // Return values as an array }
Now to use the code:
$difference = timeDifference(mktime(0, 0, 0, 9, 23, 1986)); // Specify unix timestamp in timeDifference() echo 'Time elapsed: '.$difference['years'].' years, '.$difference['months'].' months, '.$difference['days'].' days'; // Echo each variable in $difference
All you have to do is provide the timeDifference() function a unix timestamp using mktime or strtotime functions.





August 6th, 2008 at 6:20 am
egr