I'm looking for a way to calculate the average total duration (in DateInterval
form) of an event. I have the durations in DateInterval
objects, but I need to sum those up and calculate their average. Solutions I've seen so far have me adding up the different amounts by converting them to seconds, but I need to present the final form in a DateTime
form.
How can I present the average duration as a DateTime
value?
EDIT:
Setting the duration as follows (where $busyTime
and $freeTime
are DateTime objects):
$timetable[$siteID]->duration = $timetable[$siteID]->freeTime->diff($timetable[$siteID]->busyTime,true); //compare time, force to absolute (true)
Then I'm trying to sum up the durations, like so:
$totalDuration += $timetable[$siteID]->duration;
For this one, I get 129 for both the total duration AND the number of items I'm counting, which implies to me that they are all a value of 1. This is fine if so (maybe 1 second each?) but I'd like to be able to handle more than just seconds. I'm not sure if that's what is happening here.
I also tried the following, though I didn't expect it to work:
$totalDuration += $timetable[$siteID]->duration->format("Y-m-d H:i:s");
For the last one, I get 0.
You could simple create
DateTime
object with timestamp =0
; then->add()
all yourDateinterval
's to that object; fetch->getTimestamp()
and divide it by number intervals added. You will get average number of seconds; example:demo
If you wish to convert seconds to
DateInterval
object, you can just create it withPTxS
parameter:demo
But this will not calculate carry-over-points, like you see on demo. If this is a problem, you can still recalculate carry-over-points; example:
demo