PHP: Timestamp difference incorrect
The situation
I've got two timestamps.
One with the start time and one with the end time.
The start time is: 04:43:37
The end time is: 11:59:59
Now I am trying to get the difference between the dates like this:
//define timestamps
$start_time = 1297698217;
$end_time = 1297724399;
$time_diff = $end_time - $start_time;
//display times and difference
echo
'<b>Start time:</b> ' . date('d-m-Y h:i:s', $start_time) . '<br />' .
'<b>End time:</b> ' . date('d-m-Y h:i:s', $end_time) . '<br />' .
'<b>Time difference::</b> ' . date('h:i:s', $time_diff);
The result
Start time: 14-02-2011 04:43:37
End time: 14-02-2011 11:59:59
Time difference: 08:16:22
The problem
Now the problem is that the result should be 07:16:22. I've tried this with different times, but every time I'm getting the same result. One hour too much difference.
Is there an expert willing to help?
Answer
Solution:
The last one should be
gmdate
instead ofdate
:date
adjusts for your current locale, which appears to be GMT+1.gmdate
does not make that adjustment.I'm assuming that you're only planning to use this for time differences less than 24 hours.
Answer
Solution:
You're asking it to turn 1970-01-01 07:16:22 into a time string for display - there are going to be differences based on your time zone.
To make it a GMT date use gmdate() but this will still cause you issues when time differences get >24 hours.