How to transform string to time in PHP?


I have 2 strings that represent times. How to calculate the difference between the two.

$string1 = "12:04:32";
$string2 = "18:07:34";


You can use the combination of diff() methods which calculate the difference between the times and format() to format the time as desired from the DateTime class.

DateTime has been around since PHP 5.2, the diff() and createFromFormat() methods are only available in PHP 5.3


$hora1 = DateTime::createFromFormat('H:i:s', '12:04:32');
$hora2 = DateTime::createFromFormat('H:i:s', '18:07:34');

echo $hora1->diff($hora2)->format('%H horas %i minutos e %s segundos');
Scroll to Top