I have two timestamps recorded on a mysql table using php. How can I calculate the difference between these timestamps in hours using php or mysql?
3条回答 默认 最新
duanjizhan9353 2010-08-25 19:02关注If you actual hours (3600 seconds), it's just a matter of subtracting the timestamps and dividing by 3600:
$hours = ($timestamp2 - $timestamp1)/3600; $hours = floor($hours); // to round down.or similar in SQL.
If you want the "logical hours":
$tz = new DateTimezone("Europe/Lisbon"); //replace with actual timezone $d2 = new DateTime("@$timestamp2"); $d2->setTimezone($tz); $d1 = new DateTime("@$timestamp1"); $d1->setTimezone($tz); $hours = $d2->diff($d1)->h;This makes difference in case there has been a DST change between the two times. Example:
<?php $ltz = new DateTimezone("Europe/Lisbon"); date_default_timezone_set("Europe/Lisbon"); $ts2 = strtotime("31-Oct-2010 02:30:00"); $ts1 = strtotime("31-Oct-2010 00:30:00"); $d2 = new DateTime("@$ts2"); $d2->setTimezone($ltz); $d1 = new DateTime("@$ts1"); $d1->setTimezone($ltz); var_dump(floor($ts2-$ts1)/3600); var_dump($d2->diff($d1)->h);gives:
float(3) int(2)
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报