0

I'm trying to subtract two different time strings in php. The strings are extracted from a database, and have the "HH:MM:SS" format.

I have done some tests using the following code:

echo "<br>" . '$opt[2]: ' . "<br>";
var_dump($opt[2]);

echo "<br>" . 'strtotime($opt[2]): ' . "<br>";
var_dump(strtotime($opt[2]));

echo "<br>" . '$originTT[0]: ' . "<br>";
var_dump($originTT[0]);

echo "<br>" . 'strtotime($originTT[0]): ' . "<br>";
var_dump(strtotime($opt[2]));

echo "<br>" . 'date(\'H:i:s\', strtotime($opt[2]) - strtotime($originTT[0])): ' . "<br>";
var_dump(date('H:i:s', strtotime($opt[2]) - strtotime($originTT[0])));

and get the following output on the page

$opt[2]:

/var/www/html/action_trip_search_salo.php:390:string '08:42:00' (length=8)


strtotime($opt[2]):

/var/www/html/action_trip_search_salo.php:393:int 1641026520


$originTT[0]:

/var/www/html/action_trip_search_salo.php:396:string '00:16:00' (length=8)


strtotime($originTT[0]):

/var/www/html/action_trip_search_salo.php:399:int 1641026520


date('H:i:s' ,strtotime($opt[2]) - strtotime($originTT[0])):

/var/www/html/action_trip_search_salo.php:402:string '09:26:00' (length=8)

I was expecting 08:26:00, not 09:26:00. Is it related to strtotime() using UNIX time? What's the simplest way to solve this?

er3016
  • 125
  • 9
  • Take a look here, it may be helpful: https://stackoverflow.com/questions/17717911/how-to-subtract-minutes/17718000 – Serghei Leonenco Jan 01 '22 at 18:20
  • Thanks for the reply. However, the top upvoted answers from that thread use the same process I did - convert time string using strtotime(), do the operation, and convert back using date(). Some of the remaining answers also use constant time (15 min), which would not work for my problem. – er3016 Jan 01 '22 at 18:45
  • This should be what you are looking for: https://stackoverflow.com/a/44964124/1456201 – Jim Jan 01 '22 at 20:50
  • I would certainly use the `diff()` method from the native DateTime class in a professional script. – mickmackusa Jan 02 '22 at 02:51

0 Answers0