PHP: Timestamp difference incorrect

十年热恋 提交于 2019-12-23 02:31:38

问题


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?


回答1:


The last one should be gmdate instead of date:

'<b>Time difference::</b> ' . gmdate('h:i:s', $time_diff);

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.




回答2:


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.



来源:https://stackoverflow.com/questions/5018152/php-timestamp-difference-incorrect

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!