【问题标题】:get last 3 months from current month using php使用 php 从当前月份获取最后 3 个月
【发布时间】:2014-08-06 05:04:52
【问题描述】:

我想从当前月份获取最近 3 个月的名称。例如当前月份是八月。所以,我想要这些六月、七月、八月的数据。我试过这个代码echo date("F", strtotime("-3 months"));。它仅在六月返回。如何使用 php 获取当前月份的最后 3 个月?

【问题讨论】:

  • 您能否创建一个for 循环并在每次将结果添加到数组时减少减法?

标签: php


【解决方案1】:

通过使用 date 和 strtotime 函数,您实际上走在了正确的轨道上。根据您的要求在下面扩展它:

function getMonthStr($offset)
{
    return date("F", strtotime("$offset months"));
}

$months = array_map('getMonthStr', range(-3,-1));

【讨论】:

    【解决方案2】:

    简单代码:

    <?php
    
    for($x=2; $x>=0;$x--){
    echo date('F', strtotime(date('Y-m')." -" . $x . " month"));
    echo "<br>";
    }
    
    ?>
    

    从 LTroubs here 得到这个想法。

    【讨论】:

      【解决方案3】:

      应该可以的:

      function lastThreeMonths() {
          return array(
              date('F', time()),
              date('F', strtotime('-1 month')),
              date('F', strtotime('-2 month'))
          );
      }
      
      var_dump(lastThreeMonths());
      

      【讨论】:

        【解决方案4】:

        试试这个:-

        $current_date = date('F');
        for($i=1;$i<3;$i++)
        {
            ${"prev_mont" . $i} = date('F',strtotime("-$i Months"));
            echo ${"prev_mont" . $i}."</br>";
        }
        echo $current_date."</br>";
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多