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)
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥30 这是哪个作者做的宝宝起名网站
- ¥60 版本过低apk如何修改可以兼容新的安卓系统
- ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
- ¥50 有数据,怎么建立模型求影响全要素生产率的因素
- ¥50 有数据,怎么用matlab求全要素生产率
- ¥15 TI的insta-spin例程
- ¥15 完成下列问题完成下列问题
- ¥15 C#算法问题, 不知道怎么处理这个数据的转换
- ¥15 YoloV5 第三方库的版本对照问题
- ¥15 请完成下列相关问题!