skip to Main Content

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);

2

Answers


  1. First note that:

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

    As code is not instantly executed, the second Carbon::parse() might happen few microseconds after the first one and this might be 23:59.999 and then 00:00.000 so on a different date.

    So you better keep the date from start and refer to end time:

    $time_start = $start->toTimeString();
    $startTimeWithEndDate = $end->copy()->modify($time_start);
    $duration = $end->diffInMinutes($startTimeWithEndDate);
    

    Then here you can (if you need) swap the difference if end time is lower then start time:

    $time_start = $start->toTimeString();
    $startTimeWithEndDate = $end->copy()->modify($time_start);
    
    if ($startTimeWithEndDate > $end) {
        $startTimeWithEndDate->addDay();
    }
    
    $duration = $end->diffInMinutes($startTimeWithEndDate);
    
    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search