Question

I need to find the average birth date for a group of people. Say there are 5 people with the birth date of 5/14/2014 and 5 people with the birth date of 5/16/2014. The average would be 5/15/2014. I need a way to put this into a function.

The function needs to be able to handle things like 10 people born on 5/14/2014 and 50 people born on 5/18/2014. This would obviously average around 5/17/2014.

I'm thinking I could do something like this.

//date1 and date2 are the dates given
//total1 and total2 are the number of people for each date 
$time1 = strtotime($date1);
$time2 = strtotime($date2);
$total = ($time1 * $total1) + ($time2 * $total2);
$avg = $total / ($total1 + $total2);
$final = date("Y-m-d",$avg);
Was it helpful?

Solution

Just takes the dates, turn them into timestamps, add them up, divide by the number of birthdays, and the print out the date of that final timestamp.

$birthdays = array('2014-05-14','2014-05-15','2014-05-16','2014-05-17','2014-05-18');
$total_timstamp = 0;
foreach ($birthdays as $birthday) {
    $total_timstamp = bcadd($total_timstamp, (new DateTime($birthday))->format('U'));
}
$average_timestamp = bcdiv($total_timstamp, count($birthdays));
echo date('Y-m-d', $average_timestamp);

Demo

This should also work with dates in MM/DD/YYYY format.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top