【问题标题】:Calculate Months From two dates从两个日期计算月份
【发布时间】:2014-09-17 06:30:45
【问题描述】:

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

例如:

如果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 日期函数?

【问题讨论】:

标签: php date datetime monthcalendar


【解决方案1】:

这就是你要找的东西?

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

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

【讨论】:

    【解决方案2】:
    $date1 = new DateTime('2014-08-20');
    $date2 = new DateTime('2014-09-17');
    
    $diff = $date2->diff($date1);
    
    $diff->format('%m months');
    

    【讨论】:

    • 它给了我 0 个月;但正如我所说的,我需要几个月 = 2
    【解决方案3】:

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

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

    【讨论】:

    • @SandipPatel 很高兴它有帮助,实际上卡西米尔的回答也很好
    • 是的,Casimir et Hippolyte 给出了非常简短的回答,所以它也会对我和其他人有所帮助。再次感谢您的回答。
    • 当然@SandipPatel 很高兴我能提供帮助
    【解决方案4】:

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

    考虑这个例子:

    <?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

    【讨论】:

      【解决方案5】:

      你可以这样做:

      $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

      【讨论】:

      • 它给了我 6 个月的时间;但正如我所说的,我需要几个月 = 7
      • 所以它也应该计算日差?是的。
      猜你喜欢
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 2023-04-06
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多