如何使用 carbon 将时间格式化为 laravel 中的 "H:i:s"

How to format time to "H:i:s" in laravel using carbon

鉴于用户输入了 "start time" 和 "stop time",我想找出花在某个项目上的总时间。我已经能够访问花费的时间,但它以日期间隔数组的形式出现。

我只想将结果格式化为 "H:i:s"(时:分:秒)

这是来自我的控制器的代码

我已经在controller的顶部声明了Carbon的使用Class(use Carbon/Carbon;)

    $start = Carbon::parse($request->strt_time);
    $end = Carbon::parse($request->stp_time);
    $time_spent = $end->diff($start);

    $spent_time = $time_spent->format('H:i:s');

我希望输出为 00:00:00 但我得到的是字符串 "H:i:s"

diff()方法给出了CarbonInterval,它继承了DateInterval的格式化功能。文档指出每个格式字符必须以百分号 (%) 为前缀

 DateInterval::format ( string $format ) : string


 $january = new DateTime('2010-01-01');
 $february = new DateTime('2010-02-01');
 $interval = $february->diff($january);

 // %a will output the total number of days.
 echo $interval->format('%a total days')."\n";

 // While %d will only output the number of days not already covered by the
 // month.
 echo $interval->format('%m month, %d days');

所以最终的解决方案是

$end->diff($start)->format('%H:%i:%s');

来自Carbon documentation:

Difference

As Carbon extends DateTime it inherit its methods such as diff() that take a second date object as argument and returns a DateInterval instance.

We also provide diffAsCarbonInterval() act like diff() but returns a CarbonInterval instance. Check CarbonInterval chapter for more information.

因此,正如 所建议的那样,您可以这样做:

$spent_time = $end->diff($start)->format('%H:%i:%s');

为什么每个变量都加上%前缀?正如@aynber 指出的那样,the documentation 状态:

Each format character must be prefixed by a percent sign (%).

另一种选择是使用 gmdate() 助手:

$duration = $end->diffInSeconds($start);
$spent_time = gmdate('H:i:s', $duration);

或者只是:

$spent_time = gmdate('H:i:s', $end->diffInSeconds($start));