如何在php中添加时间变量


How can I do addition with time variable in php

我认为这应该很简单。

$m_time1 = strtotime('1:00:00');
$m_time2 = strtotime('5:30:00');
$m_total = $m_time1 + $m_time2;
echo date('h:i:s', $m_total);

结果是3:30:00,但应该是6:30:00

知道为什么吗?

strtotime()生成一个unix时间戳,表示从提供的时间到1970年1月1日之间的秒数。由于您没有在函数调用中指定日期,因此它假定您传递给函数时的当前日期。

因此,您上面的代码,今天运行会产生的输出

$m_time1 = 1376024400
$m_time2 = 1376040600

当你把这些加在一起时,就会得到2057年中3:30 AM的"时间"。


为了避免这种情况发生,您需要在添加时间戳之前从时间戳中减去"今天"的时间戳,然后在添加后再次添加。

$today = strtotime("TODAY");
$m_time1 = strtotime('1:00:00') - $today;
$m_time2 = strtotime('5:30:00') - $today;
$m_total = $m_time1 + $m_time2 + $today;
echo date('h:i:s', $m_total);

上述代码与6:30:00相呼应。

PHP隐藏示例