我有秒,我想像这样变换它们:0:14
、1:25
、1:10:45
没有前导零。我已经尝试过gmdate
但它有前导零。
有没有办法使用 Carbon
来做到这一点,或者我必须为此创建自定义函数?
更新:这是我当前的代码:
Carbon::now()->subSeconds($seconds)->diffForHumans(Carbon::now(), true, true);
秒数是整数,甚至可能大2000
或更多。它显示为14s
,25m
,我想0:14
,25:27
- 也显示秒数。
您可以编写如下自定义函数:
public function customDiffInHuman($date1, $date2)
{
$diff_in_humans = '';
$diff = 0;
if($hours = $date1->diffInHours($date2, null)){
$diff_in_humans .= $hours;
$diff = $hours * 60;
}
$minutes = $date1->diffInMinutes($date2, null);
$aux_minutes = $minutes;
if($hours)
$minutes -= $diff;
$diff = $aux_minutes * 60;
$diff_in_humans .= ($diff_in_humans) ? ':'.str_pad($minutes, 2, 0, STR_PAD_LEFT) : $minutes;
if($seconds = $date1->diffInSeconds($date2, null)){
if($diff)
$seconds -= $diff;
$diff_in_humans .= ':'.str_pad($seconds, 2, 0, STR_PAD_LEFT);
}
return $diff_in_humans;
}
例如,如果将此函数放在一个类或帮助程序中并调用它:
$date1 = CarbonCarbon::now()->subSeconds(14);
$date2 = CarbonCarbon::now();
echo $your_class->customDiffInHuman($date1, $date2); // This will output 00:14
$date1 = CarbonCarbon::now()->subSeconds(125);
$date2 = CarbonCarbon::now();
echo $your_class->customDiffInHuman($date1, $date2); // This will output 2:05
$date1 = CarbonCarbon::now()->subSeconds(3725);
$date2 = CarbonCarbon::now();
echo $your_class->customDiffInHuman($date1, $date2); // This will output 1:02:05