Warface
Warface

Reputation: 5119

Calculating time difference (PHP)

Here's my function

<?php    
//Find time difference
    function timeDifference($timeEnd, $timeStart){
      $tResult = strtotime($timeEnd) - strtotime($timeStart);
      return date("G:i", $tResult-3600);
    }
?>

And an example

<?php
   echo timeDifference(12:00:00,08:30:00);
?>

The results on my localhost was fine but online on my server it's showing 21:30 when it's supposed to be 3:30. What could do that?

UPDATE

Here my solution for php 5.2

<?php
//Find time difference
function timeDifference($timeEnd, $timeStart){
  $tResult = round(abs(strtotime($timeEnd) - strtotime($timeStart)));
  return gmdate("G:i", $tResult);
}
?>

Thanks for the help guys

Upvotes: 2

Views: 5690

Answers (2)

Spudley
Spudley

Reputation: 168655

If you're using PHP 5.3, it comes with a built-in date_diff() function.

It might be easier than trying to debug your own function.

By the way, the code you've given:

echo timeDifference(12:00:00,08:30:00);

is never going to work, because you haven't got quotes aruond the time strings. I assume that's a typo in the question, since you claim that the function is returning results (even if they're incorrect)

Upvotes: 4

Aaron Ray
Aaron Ray

Reputation: 838

This could be a timezone issue. Try setting the timezone with this function at the top of your PHP page:

http://www.php.net/manual/en/function.date-default-timezone-set.php

http://www.php.net/manual/en/timezones.php

Upvotes: 0

Related Questions