以两个时间戳的小时/分钟为单位的十字路口


intersection in hours/mins of two timestamps

如何在两个时间戳之间实现小时/分钟的交集?

t1 = 1970-01-01 23:00:00
t2 = 1970-01-02 11:00:00
d1 = 1970-01-01 22:30:00
d2 = 1970-01-02 01:00:00
intersection = 2h:00mins

一个不同的例子是:

t1 = 1970-01-01 23:00:00
t2 = 1970-01-02 11:00:00
d1 = 1970-01-01 08:00:00
d2 = 1970-01-01 11:30:00
intersection = 3hrs:00minutes

使用两个DateTime对象来表示两个日期。然后,您可以使用diff方法生成一个DateInterval对象,该对象又包含您想要的数据。

如果没有PHP> 5.3,则需要以下内容。它不是很漂亮,但是如果你想要小时和分钟,你可以减去两个时间戳,然后除以差值。$past是一个标志如果你想说2h:00m ago

$difference = strtotime($d1) - strtotime($d2);
$past = $difference < 0;
$difference = abs($difference);
$interval_hours = (int)($difference / 3600);
$interval_minutes = (int)(($difference % 3600) / 60);