使用 PHP 5.2 计算 2 个时间戳之间的 # 个月


Calculating # of months between 2 timestamps using PHP 5.2

可能的重复项:
在 php 中查找月份差异?

我的服务器托管多个网站,并且使用我正在使用的某些库,升级到php 5.3将非常困难。我计划在不久的将来这样做,但目前不行。

我有两个时间戳,我想计算它们之间有多少个月。PHP 5.3 具有 datetime.diff 函数,但由于我在 5.2 上,我目前无法使用它。

我有什么选择?我知道我可以通过减去时间戳来抓住秒数,然后假设每个月都有 30 天来获得月份,但我需要一个准确的结果。

非常感谢

您的帮助。

我个人选择这种方法:

$from = explode("-",date("Y-m-d",$fromStamp));
$to = explode("-",date("Y-m-d",$toStamp));
$months = ($to[0]-$from[0])*12+$to[1]-$from[1];
if( $to[1] == $from[1] && $to[2] > $from[2]) $months--; // incomplete month
if( $to[1] == ($from[1]+1)%12 && $to[2] < $from[2]) $months--; // other side
// result in $months