Search code examples
phplaraveldatelaravel-bladedate-difference

Laravel: display difference between two dates in blade


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>

Solution

  • 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.