larabarb
larabarb

Reputation: 23

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.

Upvotes: 1

Views: 214

Answers (2)

aynber
aynber

Reputation: 23011

What you'll need to do is assign both to variables, and see if the second time is before the first. If so, add a day. Then check the difference:

$date1 = Carbon::parse('23:59:59');
$date2 = Carbon::parse('00:00:01');
if($date2->lt($date1)) {
   $date2->addDay();
}

$date2->diffInSeconds($date1); // 2

Upvotes: 0

Amelia Magee
Amelia Magee

Reputation: 512

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?

Upvotes: 5

Related Questions