Calculate months between two dates using DateInterval without wrapping within a year

StackOverflow https://stackoverflow.com/questions/15362664

  •  23-03-2022
  •  | 
  •  

Вопрос

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?

Это было полезно?

Решение

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!

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top