Home > front end >  Laravel : Display the difference between the two dates by API
Laravel : Display the difference between the two dates by API

Time:10-19

DD of $job Key Statuses

The format of the dates I get back by API is the following: "startTime": "20211018094702","endTime": "20211018094738"

So I want to show the difference in hours, minutes and seconds between endTime and startTime i have try something I know it doesn't work but I can't figure out how to do it. Thank you in advance for your help

@foreach ($data['statuses'] as $job) 
    @if ($job['name'] == "************")
        @php
            $startTime = strtotime($job['startTime']) 
        @endphp


    @elseif ($job['name'] == "***********")
        @php
            $endTime = strtotime($job['endTime']);
        @endphp

        {{ ($endTime - $startTime)/3600 }}

    @endif
    
@endforeach

CodePudding user response:

You can use DateTime for calculation. I have rewritten your code. I didn't know what exactly you wanted, but you can output it as you wish.

Small hint. I would not do such calculations in the view.

@foreach ($data['statuses'] as $job) 
    @if ($job['name'] == "************")
        @php
            $startTime = $job['startTime']; 
        @endphp


    @elseif ($job['name'] == "***********")
        @php
            $endTime = $job['endTime'];
            // new calculation with datetime
            $dateTime_1 = new DateTime($startTime);
            $dateTime_2 = new DateTime( $endTime); 
            $interval = $dateTime_1->diff($dateTime_2);
            echo $interval->format('%Y years %m months %d days %H hours %i minutes %s seconds');

        @endphp

        

    @endif
    
@endforeach


Instead of strtotime you can use DateTime. This has the advantage that you then have access to the DateTime functions. For example, diff() or format() etc. With diff you can easy perform calculations between two DateTime objects. And furthermore, with format you can output the desired format or only certain elements like days etc. $dateTimeObject->('y-m-d').

Therefore, in my opinion, it is always a good choice to use datetime for date calculation. In the initial question, strtotime was used. strtotime only returns a valid timestamp object. For further calculation you would have to work with date, dateTime, carbon etc.

My absolute favourite for date calculations is and stay Carbon. https://carbon.nesbot.com/docs/

  • Related