从两个日期计算月份

时间:2014-09-17 06:30:45

标签: php date datetime monthcalendar

我需要计算两个日期的月份

例如:

如果date1 = '2014-08-20'表示2014年8月20日

&安培; date2 = '2014-09-17'表示今天的日期

然后我需要区别months = 2 (Aug + September)

同样的方式

     If `date1 = '2014-03-15'` means 15th March 2014

     &  `date2 =  '2014-09-17'`  means today date

然后我需要区别months = 7 (March + April + May + June + July + Aug + SEPT)

如何处理php日期函数?

5 个答案:

答案 0 :(得分:2)

$date1 = new DateTime('2014-08-20');
$date2 = new DateTime('2014-09-17');

$diff = $date2->diff($date1);

$diff->format('%m months');

答案 1 :(得分:2)

如果你想考虑每个月过去的时间,你可以试试这个:

$date1 = new DateTime('2014-03-15');
$date2 = new DateTime();
$date2->modify('last day of this month'); // adjust it to take into account
$int = new DateInterval('P1M'); // every month
$count = 0;
$range = new DatePeriod($date1, $int, $date2);
foreach($range as $d) {
    ++$count; // for each month incremenent
}
echo $count;

答案 2 :(得分:2)

这是你在找什么?

$date1 = new DateTime('2014-08-20');
$date2 = new DateTime('2014-09-17');

echo  $date2->format('n') - $date1->format('n') + 1;

答案 3 :(得分:0)

你可以这样做:

$first_date = '2014-03-15';
$second_date = '2014-09-17';

$date1 = strtotime($first_date);
$date2 = strtotime($second_date);

$year1 = date('Y', $date1);
$year2 = date('Y', $date2);

$month1 = date('m', $date1);
$month2 = date('m', $date2);

$diff = (($year2 - $year1) * 12) + ($month2 - $month1);

但是,为了计算日差,我们可以做如下:

$date_interval = $first_date->diff($second_date);
        echo "difference " . $date_interval->y . " years, " . $date_interval->m." months, ".$date_interval->d." days "; 

点击此链接link

答案 4 :(得分:0)

您可以通过以下方式执行此操作。

考虑这个例子:

<?php
$start    = new DateTime('2011-12-02');
$start->modify('first day of this month');
$end      = new DateTime('2012-05-06');
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
    $monthNum=$dt->format("m");
    echo $dt->format("Y").date('F', mktime(0, 0, 0, $monthNum, 10)). PHP_EOL;
}

见行动Here

参考:How to list all months between two dates