dtu11716 2018-10-19 02:08
浏览 127
已采纳

Laravel:显示刀片中两个日期之间的差异

I want to know if it is possible to show in a blade view the difference between the system date and a record of the database with date format ($ticket->start_date) without using Carbon.

For example (I know, it is not working)

<td>{{ diff(date('Y-m-d'), strtotime($ticket->start_date))}}</td>
  • 写回答

3条回答 默认 最新

  • dpmrakfbx820320638 2018-10-19 02:24
    关注

    You've got two separate problems here:

    First: how do you diff two dates. You can go high-tech or low-tech here. If you don't want to use Carbon, I suggest going low-tech:

    <?php
    // Note, this gives you a timestamp, i.e. seconds since the Epoch.
    $ticketTime = strtotime($ticket->start_date);
    
    // This difference is in seconds.
    $difference = $ticketTime - time();
    

    At this point, you've got to decide how you want to output the difference. In seconds? In hours?

    Difference: {{ $difference }} seconds
    
    Difference: {{ round($difference / 3600) }} hours
    
    Difference: {{ round($difference / 86400) }} days
    

    You'll have to do extra engineering if you want something as pretty as Carbon::diffForHumans().

    Second: This now becomes a question for you whether this is too much code for your front-end. Obviously you could reduce all of the above to a one-liner in PHP, but your co-workers may not appreciate how unreadable it becomes:

    {{ round((strtotime($ticket->start_date) - time()) / 3600) }} hours
    

    Caveats

    Using timestamps ducks the issue of dealing with timezones. For a bunch of use cases, this is sufficient; for others this is woefully inadequate. But if you want to deal with timezones, you're definitely better off using Carbon, which is better than using PHP's DateTime, but up to you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置