Php 如何将秒格式化为时间,而不显示不必要的零

Php 如何将秒格式化为时间,而不显示不必要的零,php,laravel,php-carbon,Php,Laravel,Php Carbon,我有秒,我想这样变换它们: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-也显示秒数。您可以编写如下

我有秒,我想这样变换它们:
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 = \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

那么你想要
:14
或者
14
或者什么?三个示例中只有一个示例有前导零i想要
0:14
,但不想要
00:00:14
,因为它使用的是
gmdate
,您能否显示您当前的代码和起始字符串(例如
00:00:14
=开始和
0:14
应该是输出)?嗯,我还没有找到解决问题的方法。我有
$seconds=40;//来自数据库的数据
并要格式化它们,
$seconds
可以有多大?您正在将其扩展到分钟、小时、天等?我将尝试。使用碳纤维怎么样?我想不出用碳做这件事的方法