Search code examples
phplaravelphp-carbon

How to get the minute difference between two Carbon objects ignoring the date?


I have a start date

$start = Carbon::parse('2023-03-01 10:00:00');

and an end date

$end = Carbon::parse('2023-03-02 17:00:00');

I want to get the minutes between 10:00:00 and 17:00:00 ignoring the date.

I made this working with

$time_end = $end->toTimeString();
$time_start = $start->toTimeString();
$duration = Carbon::parse($time_end)->diffInMinutes(Carbon::parse($time_start));

but with the toTimeString() I kind of leaving the Carbon object and I feel there must be a better approach.

Even if I don't find a function like that in the CarbonInterface I still feel this must be accomplished better.

Another idea I had is:

$duration = $end->diffInMinutes($start) - 24 * 60  * $end->diffInDays($start);

Solution

  • Carbon has a setDateFrom(DateTime Object) method. The method only takes the date from the argument. The time remains unchanged. The above task can be solved with one line of code as follows:

    $duration = $start->setDateFrom($end)->diffInMinutes($end);