如何获得两个日期的月份差异

时间:2014-11-16 13:05:45

标签: php date datetime

我一直在努力研究如何做到这一点,而且我已经找到了我的最后一个选择。

我只看到日期差异,但我需要得到几个月的数量。

如果我这样做

$date1 = new DateTime(date('Y-m-d'));
$date2 = new DateTime(date('2013-04-10'));
$interval = $date2->diff($date1);

$interval->format("%m months");

我得到7 months这是错误的,因为它是去年所以价值必须是19 months

1 个答案:

答案 0 :(得分:3)

实际上,当您print_r()间隔对象时,您会看到:

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

转换它:

$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;