Laravel Carbon diff未显示0年

时间:2018-02-13 14:03:41

标签: php laravel date php-carbon

我使用Carbon

在2个日期之间使用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 任何解决方案?

3 个答案:

答案 0 :(得分:5)

使用diffInYears()

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

答案 1 :(得分:0)

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

示例输出:

  

2017-12-05和2018-12-09:1年4天

     

2017-12-05和2018-02-05:2个月

答案 2 :(得分: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"