I'm using Laravel 5.3 and Carbon library.
I'm trying to compare multiple diffForHumans
results.
For example I have three differences:
3 weeks after
7 days after
2 days after
Is it possible to compare these to find minimum, maximum and average value?
In this example that would be:
I could use diff
instead of diffForHumans
if necessary (and it seems to me it's going to be to get precise results for average).
Any pointers on what too Google are appreciated since I can't find anything on this topic so I hope I'm searching for the wrong thing.
Thanks!
The output from diffForHumans
is, well, for humans and humans are, as we know, terrible calculators. Don't do it.
Given an array of \Carbon
, you can compute your values as follows:
$carbons = [ ... ];
$diffs = array_map(function ($c) { return $c->diffInSeconds(); }, $carbons);
$max = $carbons[array_search(max($diffs), $diffs)];
$min = $carbons[array_search(min($diffs), $diffs)];
$avg = array_sum($diffs)/count($diffs);
If you insist, and want to sort the output from diffForHumans
, you can key off of the modifier and the numeric value. Once ordered, you can shift the min and pop the max:
function score($c) {
$scores = [ 1 => 'second', 'minute', 'hour', 'day', 'week', 'month', 'year' ];
$diff = $c->diffForHumans();
foreach ($scores as $multiplier => $word) {
if (false !== strpos($diff, $word)) {
return $multiplier * (int)$diff;
}
}
return (int)$diff;
}
usort(
$carbons,
function ($a, $b) { return score($a) <=> score($b); }
);
Bear in mind that diffForHumans
output can be short form (eg, 'd'
instead of 'day'
), as well as translated into another language. So you have to be careful manipulating its output.
Note: the code above has only been mentally compiled.