Reputation: 22674
How is it possible to make the code below convert days in hours?
$timestart = date_create('02/11/2011' . $row->timestart); //$row->timestart returns time in 00:00:00 format
$timestop = date_create('02/11/2011' . $row->timestop); //$row->timestop returns time in 00:00:00 format
date_add($timestop, date_interval_create_from_date_string('2 days')); //add 2 days
$date_diff = date_diff($timestart, $timestop);
echo "Timespan: ";
echo $date_diff->format('%h hours');
echo "<br />";
How can I get the hours:minutes:seconds
elapsed? I'm trying to stay with the date_diff
function.
Upvotes: 0
Views: 10568
Reputation: 174957
The DateInterval
object, returned by date_diff
stores each period of time separately, seconds, minutes, hours, days, months and years.
Since the difference is 2 days, the hours property is 0, which is what you get.
Upvotes: 1
Reputation: 106385
The result of date_diff() is an object of DateInterval class. Such object has a very useful property - $days
: it's total number of days between the starting and the ending dates. Besides, it stores (as its public properties) the difference in hours, minutes and seconds.
So, I suppose, what you need is just extract values of these properties from $date_diff variable, then add 24*$days
to the hours number. ) All this can be wrapped into a simple function:
function hms_date_diff(DateInterval $date_diff) {
$total_days = $date_diff->days;
$hours = $date_diff->h;
if ($total_days !== FALSE) {
$hours += 24 * $total_days;
}
$minutes = $date_diff->i;
$seconds = $date_diff->s;
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}
As for DateDiff::format, the doc says...
The DateInterval::format() method does not recalculate carry over points in time strings nor in date segments.
Upvotes: 6