dongtazu3080 2016-10-31 09:03 采纳率: 100%
浏览 64
已采纳

错误日期PHP

i have these code,

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

but, I have returned by this message:

An uncaught Exception was encountered

Type: Exception

Message: DatePeriod::__construct(): This constructor accepts either (DateTimeInterface, DateInterval, int) OR (DateTimeInterface, DateInterval, DateTime) OR (string) as arguments.

anyone can help me?

  • 写回答

3条回答 默认 最新

  • duanliaoyin3171 2016-10-31 09:13
    关注

    You have syntax error and object initialization error. Here is the correction:

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

    Problem 1: DatePeriod constructor accepts DateTime object. Please check manual http://php.net/manual/en/class.dateperiod.php

    Problem 2: you need $periodsvariable as you used in foreach

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化