我正在使用此函数来获取两个日期之间的月份差异.
$interval = date_diff(date_create('2015-10-08'), date_create('2014-10-10'));
$total_months = $interval->format('%m');
Run Code Online (Sandbox Code Playgroud)
结果: 11(那是正确的!)
但是,当差异超过一年时,那么,
$interval = date_diff(date_create('2015-11-08'), date_create('2014-10-10'));
$total_months = $interval->format('%m');
Run Code Online (Sandbox Code Playgroud)
结果: 0(那是错的!)
为什么它会返回0?有什么方法可以让我在任何两个日期之间有所区别吗?谢谢!
2015-11-08 to 2014-10-10是12几个月成为一年.所以它返回0月份.计算从$interval当时添加(year * 12)到月数的年数.这里的例子......
$interval = date_diff(date_create('2015-11-08'), date_create('2014-10-10'));
$year = $interval->format('%Y');
echo $total_months = $interval->format('%m') + $year * 12;
Run Code Online (Sandbox Code Playgroud)