Search code examples
phplaraveltimedifference

How to calculate in PHP the difference in seconds between 2 times (not datetimes) just times. Laravel // PHP // Carbon


Here is an example to make the issue clear. Both below examples are giving wrong difference:

// gives 86398 while the correct is 2sec
$diff_in_sec = strtotime('23:59:59') - strtotime('00:00:01'); 

// again gives 86398 while the correct is 2sec.
$diff_in_sec = Carbon::parse('00:00:01')->diffInSeconds(Carbon::parse('23:59:59')); 

What I want is for 23:59:59 compared with 00:00:01 to return 2 seconds difference, and 00:00:01 compared with 23:59:59.


Solution

  • You will need to convert these to datetime unfortunately. How is php to know that 23:59:59 and 00:00:01 do not occur on the same day?