错误日期期间 PHP

Mau*_*oto 0 php date intervals

我有这些代码,

  $end = strtotime ('last day of previous month') ;
  $start = strtotime ("-1 year +1 day", $end) ;

    $new ['first'] =  date ('Y-m-d',$start) ;
    $new ['last'] = date ('Y-m-d',$end) ;

    $interval = DateInterval::createFromDateString ('1 month') ;
    $period = new DatePeriod($start, $interval, $end) ;

    foreach ($periods as $period) {
      print_r($period -> date_format('Y-m')) ; echo "<br>";
    }
Run Code Online (Sandbox Code Playgroud)

但是,我已通过此消息返回:

遇到未捕获的异常

类型:异常

消息:DatePeriod::__construct():此构造函数接受 (DateTimeInterface、DateInterval、int) 或 (DateTimeInterface、DateInterval、DateTime) 或 (字符串) 作为参数。

有人可以帮助我吗?

小智 5

您有语法错误和对象初始化错误。这是更正:

$end = strtotime ('last day of previous month') ;
$start = strtotime ("-1 year +1 day", $end) ;
$new['first'] =  date ('Y-m-d', $start) ;
$new['last'] = date ('Y-m-d', $end) ;

$interval = DateInterval::createFromDateString ('1 months') ;

$periods = new DatePeriod(new DateTime($new['first']), $interval, new DateTime($new['last'])) ;

foreach ($periods as $period) {
    print_r($period->format('Y-m')) ; echo "<br>";
} 
Run Code Online (Sandbox Code Playgroud)

问题 1:DatePeriod构造函数接受 DateTime 对象。请查看手册http://php.net/manual/en/class.dateperiod.php

问题 2:您需要$periods在 foreach 中使用的变量