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 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题