Reputation: 140
I have a database which contains posts that have both a creation date(unix timestamp) and a publication date(unix timestamp). I want to calculate the average time it takes a post to be published after its created. I guess im way off, but this is what i got so far:
$times = array();
foreach($posts as $post) {
$timeBetween = $post->publicationDate - $post->creationDate;
array_push($times, $timeBetween);
}
$average = array_sum($times) / count($times);
echo date("H:m:s",mktime(0,0,$average,0,0,0));
My optimal output would be something like: 1 day, 12 hours, 13 second..
Anyone?
Appreciate any help!
Upvotes: 1
Views: 1640
Reputation: 78
Why don't you use the foreach-loop like this:
$time = 0;
foreach ( $posts as $post ) {
$time += $post->publicationDate - $post->creationDate;
}
$average = $time / count( $posts );
This way you don't need to use an array, and you got the same result.
If you want to show it like 2 days, 4 hours, 43 minutes and 2 seconds
you can calculate it like this:
// 1 day = 24 hours * 60 minutes * 60 seconds = 86400 seconds
$days = floor( $average / 86400 );
$hours = floor( ( $average % 86400 ) / 3600 );
$minutes = floor( ( $average % 3600 ) / 60 );
$seconds = $average % 60;
echo $days . ' day' . ( $days > 0 ? 's' : '' ) . ', ';
echo $hours . ' hour' . ( $hours > 0 ? 's' : '' ) . ', ';
echo $minutes . ' minute' . ( $minutes > 0 ? 's' : '' ) . ', ';
echo $seconds . ' second' . ( $seconds > 0 ? 's' : '' );
Upvotes: 1
Reputation: 18430
date()
is not the correct tool for this job. date()
doesn't understand a period of time like 2D 3H 27M
, it only understands points in time.
In your code $average
will contain a number of seconds, so you should finish with something like:-
$h = floor($average/3600);
$average -= $h*3600;
$m = floor($average/60);
$average -= $m*60;
$s = floor($average);
echo "$h:$m:$s";
Upvotes: 2