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)
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
- ¥200 求博主教我搞定neo4j简易问答系统,有偿
- ¥15 nginx的使用与作用
- ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
- ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
- ¥15 ensp路由器启动不了一直报#
- ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
- ¥15 ats2837 spi2从机的代码
- ¥200 wsl2 vllm qwen1.5部署问题
- ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了