如何在php中从两个时间戳计算准确的小时数


how to calculate exact hours from two timestamp in php?

我需要从两个时间戳中获得小时数的差异。你能告诉我如何使用php来完成吗?

提前谢谢。

问候,

$hours = (abs(strtotime($timestamp1)-strtotime($timestamp2)) / 60) / 60;

您可以将时间戳的值输入到strtotime()中,这将获得自1970年以来以秒为单位的UNIX时间戳。它将是两个大的整数值。然后在这两个值之间做减法,并将其转换为您想要得到的值。例如

分钟、小时、天、周等…通过进行正常的*60、*60、*24、*7计算

使用strtotime将时间戳转换为秒,减去它们,使用abs获得绝对值(此处没有负数!),除以3600秒(1小时),然后round达到您想要的精度。

$difference = round(abs(strtotime($stamp_one) - strtotime($stamp_two)) / 3600, 2);