Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Stallyons Tester's avatar

Difference between two times without date

How can i get difference between two times without date. I.e departure time = 07:00:00 arrival time = 03:00:00 (Midnight) expected difference = 20 hours

Note : the format is in 24 hours.

when i'm trying to get difference I'm getting wrong difference

$departure = $schedule->terminals->where('terminal_id',$request['from'])->first()->departure_time;
$arrival = $schedule->terminals->where('terminal_id',$request['to'])->first()->arrival_time;
dd(Carbon::parse($departure)->diffInHours(Carbon::parse($arrival)));
// 4 hours which wrong
0 likes
6 replies
Mareco's avatar

Hi @stallyons

do you think, it is possible to do diff your times correctly, if you don't have dates with your times? How can Carbon or any other library know, that 03:00:00 is after midnight from your data?

Stallyons Tester's avatar

@Mareco I know its not possible to do this without knowing dates but I'm here to know if someone tell me other approach to do this logic.

tykus's avatar

You can't really do this without the date parts; e.g. you could assume that the departure time should be less than arrival time otherwise add a day to $arrival...

if ($arrival->lte($departure)) {
  $arrival->addDays(1);
}

$departure->diffInHours($arrival);

...but this breaks down if the total travel time is >= 24 hours; then what should you assume? Also, what happens if/when timezones are taken into account?

Ultimately, to get the difference between two times, you need to know more that just the hours and minutes!

1 like
Stallyons Tester's avatar
Level 1

Issue Solved. If difference is negative add day to date.

$diff = Carbon::parse($departure)->diffInHours(Carbon::parse($arrival),false);
$arrival_date = $diff < 0 ? $date->toImmutable()->addDay()->format('Y-m-d') : $date->format('Y-m-d');
tykus's avatar

@Stallyons Tester this is basically the same solution as I described above, and still is vulnerable to timezones and travel times >= 24 hours.

1 like

Please or to participate in this conversation.