Question

I am aware this topic is pretty exhausted, but obviously not quite enough!

$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

How do you calculate the number of months between two dates without wrapping within a 12 month scale?

Was it helpful?

Solution

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top