Laravel Carbon diff 未显示 0 年

Laravel Carbon diff not show 0 years

我使用 Carbon 在两个日期之间使用 diff() 函数

$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');

结果

0年2个月零4天

我想要这个结果

2个月零4天

因为年数为0 有什么解决办法吗?

使用diffInYears():

$format = $fecha2->diffInYears($fecha1) > 0 ? '%y years, %m months and %d days' : '%m months and %d days';
$resta = $fecha2->diff($fecha1)->format($format);

更通用的解决方案。它将分别存储每种类型的差异(年、月、日),并且仅在它不同于 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);

Demo

示例输出:

For 2017-12-05 and 2018-12-09: 1 years, 4 days

For 2017-12-05 and 2018-02-05: 2 months

您应该考虑当您的差异包括 0 天或 0 个月时会发生什么。您必须涵盖很多可能性:

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')
);

结果会是

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"