【问题标题】:How to format time to "H:i:s" in laravel using carbon [duplicate]如何使用碳在laravel中将时间格式化为“H:i:s”[重复]
【发布时间】:2019-09-27 12:31:38
【问题描述】:

鉴于用户输入“开始时间”和“停止时间”,我想找出在项目上花费的总时间。我已经能够访问所花费的时间,但它以日期间隔数组的形式出现。

我只想将结果格式化为“H:i:s”(Hour:Minute:Seconds)

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

我已经在控制器顶部声明了使用 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”

【问题讨论】:

  • var_dump($time_spent); 会得到什么?
  • 您尝试过什么调试问题?您是否尝试过转储所有变量以检查其真实内容?
  • 我得到一个字符串 'H:i:s' - @aynber
  • 你的格式字符串应该是'%H:%i:%s'

标签: php laravel datetime php-carbon


【解决方案1】:

来自Carbon documentation

Difference

随着 Carbon 扩展 DateTime,它继承了它的方法,例如 diff() 将第二个日期对象作为参数并返回一个 DateInterval 实例。

我们还提供 diffAsCarbonInterval() 行为类似于 diff() 但返回 CarbonInterval 实例。查看CarbonInterval章节了解更多信息 信息。

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

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

为什么% 在每个变量中都有前缀?正如@aynber 指出的那样,the documentation 声明:

每个格式字符必须以百分号 (%) 为前缀。

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

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

或者只是:

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

【讨论】:

    【解决方案2】:

    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');
    

    【讨论】:

    • 请在您的代码中添加一些解释,以便其他人可以从中学习。我看不出和原来的代码有什么区别
    • 这个答案是正确的,但缺乏解释。 $time_spent 是一个 CarbonInterval,它继承了 DateInterval 的格式函数。 The documentation 声明 Each format character must be prefixed by a percent sign (%).
    • 非常感谢大家...它现在工作...我真的很感激...
    • @Micsedinam 如果可行,请接受此答案。
    • @AkashKumarVerma 请在您的代码中添加一些解释,以便其他人可以从中学习
    猜你喜欢
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    相关资源
    最近更新 更多