Laravel Carbon DiffForHumans选项(年,月,天)

flvlnr44  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(156)

我已经通读了the documentation of DiffForHumans,它非常简单,但是有没有一种方法可以自定义打印日期:

  • 13年1个月10天
  • 01年11个月01天

在哪里它将尊重年/年,月/月,日/天?

  • 方法一:
$date = Carbon::parse('2010-08-29');
$formattedDate = $date->diffForHumans(['parts' => 3, 'join' => ', '];

字符串
将打印出13 years, 1 month, 4 weeks ago

  • 方法二:
$date = Carbon::parse('2010-08-29');
$formattedDate = $date->diff(now())->format('%y Year, %m Months and %d Days')


将打印出13 Year, 1 Months and 28 Days

  • 方法3(备份选项):
$date = Carbon::parse('2010-08-29');
$formattedDate = $date->diff(now())->format('%y Year(s), %m Month(s) and %d Day(s)')


将打印出13 Year(s), 1 Month(s) and 28 Day(s)
有没有一个普通的PHP类可以完成类似的事情?

修改后的接受方案:

public function customDiffForHumans(Carbon $date) : string
    {
        $diff = $date->diff(now());

        $years  = $diff->y ? $diff->y . ' Year' . ($diff->y > 1 ? 's' : '') : '0 Years';
        $months = $diff->m ? $diff->m . ' Month' . ($diff->m > 1 ? 's' : '') : '0 Months';
        $days   = $diff->d ? $diff->d . ' Day' . ($diff->d > 1 ? 's' : '') : '0 Days';

        return implode(', ', array_filter([$years, $months, $days]));
    }

cbwuti44

cbwuti441#

这是用于处理相同问题的自定义函数:

function customDiffForHumans(DateTime $date) {
    $now = new DateTime();
    $diff = $date->diff($now);

    $years = $diff->y ? $diff->y . ' Year' . ($diff->y > 1 ? 's' : '') : null;
    $months = $diff->m ? $diff->m . ' Month' . ($diff->m > 1 ? 's' : '') : null;
    $days = $diff->d ? $diff->d . ' Day' . ($diff->d > 1 ? 's' : '') : null;

    return implode(', ', array_filter([$years, $months, $days]));
}

$date = new DateTime('2010-08-29');
return customDiffForHumans($date);

字符串

8wtpewkr

8wtpewkr2#

您可以跳过不需要的单元:

$date = Carbon::parse('2010-08-29');
$formattedDate = $date->diffForHumans([
    'parts' => 3,
    'join' => true,
    'skip' => 'week',
]);

字符串
旁注:'join' => true自动使用,-and(如果您选择另一种语言,请翻译)

p3rjfoxz

p3rjfoxz3#

你可以试试这个例子:

Carbon::parse('07-09-2014')->locale('en')->diffForHumans(
    [
        'parts' => 3,
        'join' => ', ',
        'skip' => 'week',
        'syntax' => Carbon::DIFF_ABSOLUTE,
    ]
)

字符串
预期输出:

"9 years, 1 month, 20 days"


但是,是的,这个例子将不包括前导零和StudlyCase(您可以使用标题)问题

相关问题