计算PHP中2个时间戳之间的差异 [英] calculate the difference between 2 timestamps in php

查看:95
本文介绍了计算PHP中2个时间戳之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表中使用2个时间戳 starttime数据类型-时间戳记,并作为当前时间戳记. endtime数据类型时间戳,默认为0000-00-00 00:00:00

I am using 2 timestamp in my table which is starttime datatype- timestamp and as current timestamp. endtime datatype-timestamp and default as 0000-00-00 00:00:00

如何计算php中2个时间戳之间的差异 开始时间:2016-11-30 03:55:06 结束时间:2016-11-30 11:55:06

how to calculate the difference between 2 timestamps in php starttime:2016-11-30 03:55:06 endtimetime: 2016-11-30 11:55:06

推荐答案

任何程序方法都应避免. 使用OOP方法处理日期时间差:

Any procedural way should be avoided. Use OOP method for date time difference:

$datetime1 = new DateTime('2016-11-30 03:55:06');//start time
$datetime2 = new DateTime('2016-11-30 11:55:06');//end time
$interval = $datetime1->diff($datetime2);
echo $interval->format('%Y years %m months %d days %H hours %i minutes %s seconds');//00 years 0 months 0 days 08 hours 0 minutes 0 seconds

您可以根据需要设置差异格式.

You can setup difference format as per your needs.

%Y - use for difference in year
%m - use for difference in months
%d - use for difference in days
%H - use for difference in hours
%i - use for difference in minutes
%s - use for difference in seconds

您可以根据需要删除任何上述值.例如,如果您只对时差感兴趣,并且知道时差不能超过24小时,则仅使用%H.

You can remove any of above values as per your need. For example if you only are interested in hour difference and you know that difference cant be more than 24 hours then use only %H.

如果要以秒为单位求和,则可以使用:

If you want to have total difference in seconds then you can use:

echo $difference_in_seconds = strtotime('2016-11-30 11:55:06') - strtotime('2016-11-30 03:55:06');//28800

取决于您的需要和您想要时差的最终格式.

Depends upon your need and the final format in which you want to have time difference.

供参考检查: http://php.net/manual/en/datetime.diff.php

我希望对您有帮助

这篇关于计算PHP中2个时间戳之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆