I don't think the last solution you posted gives the result you want. It gives totals, not an accumulation of different units. That can be remedied by taking the remainder (modulus division) as shown in the code I posted here and in my last post.
Also, rounding can introduce extra time. For example, rounding a duration of 90 seconds (1.5 minutes) yields 2 minutes instead of 1 minute. Therefore, the quotients must be truncated with floor(). The floor() function rounds away from zero for negative numbers, which can cause off-by-one errors; so the duration should be a positive number. Get the absolute value of the time difference with abs().
You can, however, work from the bottom up (minutes, hours, days) as you did.
Code: Select all
<?php
define('SECONDS_PER_MINUTE', 60);
define('MINUTES_PER_HOUR', 60);
define('HOURS_PER_DAY', 24);
$now = time();
$then = strtotime('2012-02-12 22:20:24');
$seconds = abs($now - $then);
$minutes = floor($seconds / SECONDS_PER_MINUTE);
$seconds %= SECONDS_PER_MINUTE;
$hours = floor($minutes / MINUTES_PER_HOUR);
$minutes %= MINUTES_PER_HOUR;
$days = floor($hours / HOURS_PER_DAY);
$hours %= HOURS_PER_DAY;
echo "$days days, $hours hours, $minutes minutes, $seconds seconds\n";
Given that it takes the least code and it is closest to the code you started this thread with, I would suggest the first solution I posted (DateTime). But use whatever you are comfortable with, as long as it works.