代码之家  ›  专栏  ›  技术社区  ›  amit sutar

如何在php中设置前3个月?

  •  -2
  • amit sutar  · 技术社区  · 6 年前

    目前,我正在使用for循环获取此输出,以查看下一个3 按当前月份列出的月份:

    $this_month = mktime(0, 0, 0, date('m',strtotime($endDate)), 1, date('Y',strtotime($endDate)));
    for ($i = 0; $i > 3; $i++) 
    {
        $to_date = date('F Y', strtotime($i++.' month', $this_month)) . '';
    }  
    

    enter image description here

    如图所示,我将得到2018年3月至2018年5月等。现在,如果我得到2018年3月,那么我想显示2018年1月至2018年3月等。如何获取此类数据。

    2 回复  |  直到 6 年前
        1
  •  0
  •   Peter    6 年前

    下面的方法将循环并修改 DateTime 进行此操作时对象。它将在每个循环中回显您的日期,从而在过去的3个月内显示每个月。

    // Date as a string
    $sDate = '2018-04-01';
    
    // Create a DateTime object
    $oDate = DateTime::createFromFormat('Y-m-d', $sDate);
    
    // Get the previous 3 months
    for ($i = 1; $i < 3; $i++) {
        $oDate->modify('-1 month');
        echo $oDate->format('F Y');
    }
    
        2
  •  2
  •   ᴄʀᴏᴢᴇᴛ    6 年前

    你可以用 DateTime::sub() DateInterval

    这样地:

    $date = new DateTime($endDate); // create the dateTime object
    $date->sub(new DateInterval('P3M')) // substract 3 months to this date
    $to_date =  $date->format('F Y');