如何在不显示不必要的零的情况下将秒数格式化

问题描述 投票:1回答:1

我有几秒钟,我想像这样变换它们:0:141:251:10:45没有前导零。我已经尝试过使用gmdate,但它有前导零。

有没有办法使用Carbon这样做,或者我必须为此创建自定义函数?

更新:这是我目前的代码:

Carbon::now()->subSeconds($seconds)->diffForHumans(Carbon::now(), true, true);

并且秒数是整数,甚至可能是大2000或更多..它显示为14s25m,我想成为0:1425:27 - 显示秒数。

php laravel php-carbon
1个回答
1
投票

您可以编写这样的自定义函数:

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;
}

如果您将此函数放在其中一个类或Helper中并调用它,例如:

$date1 = \Carbon\Carbon::now()->subSeconds(14);
$date2 = \Carbon\Carbon::now();    
echo $your_class->customDiffInHuman($date1, $date2); // This will output 00:14

$date1 = \Carbon\Carbon::now()->subSeconds(125);
$date2 = \Carbon\Carbon::now();    
echo $your_class->customDiffInHuman($date1, $date2); // This will output 2:05

$date1 = \Carbon\Carbon::now()->subSeconds(3725);
$date2 = \Carbon\Carbon::now();    
echo $your_class->customDiffInHuman($date1, $date2); // This will output 1:02:05
© www.soinside.com 2019 - 2024. All rights reserved.