I've been trying to research how to do this and I've come to my last option SO.
I only saw getting the difference of dates in days but I need to get the number of months.
if I do this
$date1 = new DateTime(date('Y-m-d'));
$date2 = new DateTime(date('2013-04-10'));
$interval = $date2->diff($date1);
$interval->format("%m months");
I get 7 months
which is wrong because it is last year so the value must be 19 months
.
Actually, when you print_r()
the interval object, you'll see this:
DateInterval Object
(
[y] => 1
[m] => 7 // that 7 months is just a component of it
[d] => 6
[h] => 14
[i] => 12
[s] => 9
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 585
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
// its 1 year 7 months
To convert it:
$date1 = new DateTime(); // no need to put `date(Y-m-d)` just create that object, its already undestood its today
$date2 = new DateTime('2013-04-10');
$interval = $date2->diff($date1);
echo '<pre>' . print_r($interval, true) . '</pre>';
$months = $interval->m + ($interval->y * 12);
echo $months;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.