Reputation: 414
I use diff() function between 2 dates using Carbon
$fecha1 = \Carbon\Carbon::parse('2017-12-05');
$fecha2 = \Carbon\Carbon::parse('2018-02-09');
$resta = $fecha2->diff($fecha1)->format('%y years, %m months and %d days');
Result
0 years, 2 months and 4 days
I would like this result
2 months and 4 days
Because years is 0 Any solution?
Upvotes: 1
Views: 1672
Reputation: 24276
You should consider what happens when your difference includes 0 days or months. There are plenty possibilites which you must cover:
function getDifference(string $start, string $end): string
{
$formatted = (new DateTime($end))->diff(new DateTime($start))->format('%y years, %m months, %d days');
$nonZeros = preg_replace('/(?<!\d)0\s?[a-z]*,\s?/i', '', $formatted);
$commaPosition = strrpos($nonZeros, ',');
return $commaPosition ? substr_replace($nonZeros, ' and', $commaPosition, 1) : $nonZeros;
}
var_dump(
getDifference('2017-12-05', '2018-02-09'),
getDifference('2017-12-05', '2017-12-09'),
getDifference('2013-12-05', '2017-12-09'),
getDifference('2013-12-05', '2017-10-09')
);
The result would be
string(19) "2 months and 4 days"
string(6) "4 days"
string(18) "4 years and 4 days"
string(29) "3 years, 10 months and 4 days"
Upvotes: 0
Reputation: 9937
A more generic solution. It will store separately each type of diff (year, month, day), and only display it if it's different than 0.
<?php
$fecha1 = \Carbon\Carbon::parse('2017-12-05');
$fecha2 = \Carbon\Carbon::parse('2018-02-09');
$diff = $fecha2->diff($fecha1);
$diffByType = [
"years" => $diff->format("%y"),
"months" => $diff->format("%m"),
"days" => $diff->format("%d"),
];
$output = [];
foreach ($diffByType as $type => $diff) {
if ($diff != 0) {
$output[] = $diff." ".$type;
}
}
echo implode(", ", $output);
Sample outputs:
For 2017-12-05 and 2018-12-09: 1 years, 4 days
For 2017-12-05 and 2018-02-05: 2 months
Upvotes: 0
Reputation: 163788
Use diffInYears()
:
$format = $fecha2->diffInYears($fecha1) > 0 ? '%y years, %m months and %d days' : '%m months and %d days';
$resta = $fecha2->diff($fecha1)->format($format);
Upvotes: 5