What can use for DateTime::diff() for PHP 5.2?
Spudley's answer doesn't work for me--subtracting any DateTime from another gives 0 on my system.
I was able to get it to work by using DateTime::format with the 'U' specifier (seconds since Unix epoch):
$start = new DateTime('2010-10-12');$end = new DateTime();$days = round(($end->format('U') - $start->format('U')) / (60*60*24));
This works on both my dev system (5.3.4) and my deployment system (5.2.11).
I just needed that ( unfortunately ) for a WordPress plugin. This I use the function in 2 times:
In my class calling ->diff() ( my class extends DateTime, so $this is the reference DateTime )
function diff ($secondDate){ $firstDateTimeStamp = $this->format("U"); $secondDateTimeStamp = $secondDate->format("U"); $rv = ($secondDateTimeStamp - $firstDateTimeStamp); $di = new DateInterval($rv); return $di;}
Then I recreated a fake DateInterval class ( because DateInterval is only valid in PHP >= 5.3 ) as follows:
Class DateInterval { /* Properties */ public $y = 0; public $m = 0; public $d = 0; public $h = 0; public $i = 0; public $s = 0; /* Methods */ public function __construct ( $time_to_convert /** in seconds */) { $FULL_YEAR = 60*60*24*365.25; $FULL_MONTH = 60*60*24*(365.25/12); $FULL_DAY = 60*60*24; $FULL_HOUR = 60*60; $FULL_MINUTE = 60; $FULL_SECOND = 1;// $time_to_convert = 176559; $seconds = 0; $minutes = 0; $hours = 0; $days = 0; $months = 0; $years = 0; while($time_to_convert >= $FULL_YEAR) { $years ++; $time_to_convert = $time_to_convert - $FULL_YEAR; } while($time_to_convert >= $FULL_MONTH) { $months ++; $time_to_convert = $time_to_convert - $FULL_MONTH; } while($time_to_convert >= $FULL_DAY) { $days ++; $time_to_convert = $time_to_convert - $FULL_DAY; } while($time_to_convert >= $FULL_HOUR) { $hours++; $time_to_convert = $time_to_convert - $FULL_HOUR; } while($time_to_convert >= $FULL_MINUTE) { $minutes++; $time_to_convert = $time_to_convert - $FULL_MINUTE; } $seconds = $time_to_convert; // remaining seconds $this->y = $years; $this->m = $months; $this->d = $days; $this->h = $hours; $this->i = $minutes; $this->s = $seconds; }}
Hope that helps somebody.
I use this, seems to work alright - obviously you can add a second parameter to make it more flexible:
function GetDateDiffFromNow($originalDate) { $unixOriginalDate = strtotime($originalDate); $unixNowDate = strtotime('now'); $difference = $unixNowDate - $unixOriginalDate ; $days = (int)($difference / 86400); $hours = (int)($difference / 3600); $minutes = (int)($difference / 60); $seconds = $difference; // now do what you want with this now and return ...}