I am trying to calculate the difference in months between two dates, but in a more specific way.
For example, I have two dates: 2017-11-01 and 2018-01-31 What I need as a result is 3 months. Meaning, there are 3 full billing months between these two dates.
Here is how it's supposed to work:
- Month 1: 2017-11-01 until 2017-11-30
- Month 2: 2017-12-01 until 2017-12-31
- Month 3: 2018-01-01 until 2018-01-31
I have tried the diff method in the DateTime class, it produces something that doesn't help much. Here is an example
<?php
$date1 = DateTime::createFromFormat('Y-m-d H:i:s', '2017-11-01 00:00:00');
$date2 = DateTime::createFromFormat('Y-m-d H:i:s', '2018-01-31 00:00:00');
$diff = $date1->diff($date2);
print_r($diff)
result:
DateInterval Object
(
[y] => 0
[m] => 2
[d] => 30
[h] => 0
[i] => 0
[s] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 91
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
It shows 2 months and 30 days.
However, in a slightly different scenario
$date1 = DateTime::createFromFormat('Y-m-d H:i:s', '2017-11-01 00:00:00');
$date2 = DateTime::createFromFormat('Y-m-d H:i:s', '2018-01-30 00:00:00');
The diff between these two dates should show 2 months and 30 days, not 3 months.
Any help or ideas would be greatly appreciated.