Code Demon Code Demon - 1 year ago 71
PHP Question

get the difference in time between two given time

I'm trying to get the difference in time between two given times e.g. first time '17:00:01' and then second time '17:47:25' and here's what I tried so far,

$start_time = "17:00:01";
$end_time = "17:47:25";

echo $start_time->diff($end_time);

But seem's unfortunately not working, any help, ideas please?

My expected output must be like, if no difference in hours but there's difference in minutes and seconds then, "22 mins and 15 secs", If no difference in minutes but have difference in hours then, "2 hrs and 10 secs" but if only seconds in difference then, "22 secs".

Answer Source

String in php is not object, so can't call diff method on it.

Use diff method, you must change the string to DateTime object.

If you want to compare time difference in same day, you could try:

$start_time = "17:00:01";
$end_time = "17:47:25";

$start_datetime = new DateTime(date('Y-m-d').' '.$start_time);
$end_datetime = new DateTime(date('Y-m-d').' '.$end_time);