3

我知道这个话题已经很累了,但显然还不够!

$temp_d1 = new DateTime(date('Y-m-d', $fromTime)); // 2012-01-01
$temp_d2 = new DateTime(date('Y-m-d', $endTime)); // 2013-02-01
$interval = $temp_d2->diff($temp_d1); 
$monthsAhead = $interval->format('%m'); // returns 1, but I am expecting 13

你如何计算两个日期之间的月数,而不是在 12 个月的范围内换行?

4

1 回答 1

21

I was confusing exactly what:

$monthsAhead = $interval->format('%m');

does.

Obviously, format('%m') is just formatting the month component of the DateInterval object, not necessarily 'give me the interval as a number of months'.

In my case, I was looking for/to do this:

$monthsAhead = $interval->m + ($interval->y * 12);

http://www.php.net/manual/en/class.dateinterval.php

Hope this helps other fools in the future!

于 2013-03-12T13:41:54.937 回答