【问题标题】:Error when trying to format dates using an array,PHP尝试使用数组格式化日期时出错,PHP
【发布时间】:2017-06-15 17:40:25
【问题描述】:

我有一个日期数组,我想给出格式“Y-m-d”,但是当我尝试时,我得到了错误

"在数组上调用成员函数format()"

我之前所做的是将两个日期传递给一个返回时间间隔的函数,例如,如果我给出以下两个日期:

2017-06-05 | 2017-06-10

这个函数以 Y-m-d 格式返回我

"2017-06-06,2017-06-07,2017-06-08 ...

我之前格式化结果没有问题,但是,现在我发送了一个数组,它已经停止工作,这是我的代码

      public function testArray(Request $request)
          {
            if ($request!="" && $request->idUser!="") 
            {
             $timeslot= new Timeslot;
             $idUser=$request->idUser;
             $fecha1=$request->fecha2;//array
             $fecha2=$request->fecha1;//array

             $slotD=$request->slotH;//array
             $i=0;
             $k=0;
             $j=0; 
             foreach ($fecha1 as $key => $value) {
                $date1[$k]=date('Y-m-d', strtotime($value));
              $k++;
             }
             foreach ($fecha2 as $key => $value) {
               $date2[$i]=date('Y-m-d', strtotime($value));
              $i++;
             }


             foreach ($slotD as $key => $value) {
                $value=str_replace("minutos","minutes",$value);
                $slot[$j]=$value;
               $j++;
             }

             $array=array("fechaInicio"=>$date1,"fechaFin"=>$date2,"slot"=>$slot);

             for($l=0;$l<count($date1);$l++)
             {
              $datePeriod["periodo"][]=$timeslot->returnDates($date1[$l],$date2[$l]);//this method give me an array with date intervals
                }
             $dates=array();
             $m=0;

             foreach ($datePeriod as $key => $value)
              {

                $dates[$m][$key]=$value->format('Y-m-d');//ERROR

                $m++;

              }







          }

           return $dates; 
          }

函数returnDates就是这个

function returnDates($fromdate, $todate) {
                    $fromdate =  DateTime::createFromFormat('Y-m-d', $fromdate);
                    $todate =  DateTime::createFromFormat('Y-m-d', $todate);
                    return new   DatePeriod(
                        $fromdate,
                        new  DateInterval('P1D'),
                        $todate->modify('+1 day')
                    );
                }

当我使用变量 $ datePeriod 作为公共变量时,我得到了我想要的结果

for($l=0;$l<count($date1);$l++)
   {
    $datePeriod=$timeslot->returnDates($date1[$l],$date2[$l]);
      }




Result:
    [["2017-06-17"],{"1":"2017-06-18"},{"2":"2017-06-19"},{"3":"2017-06-20"},{"4":"2017-06-21"}]

当我将变量转换为关联数组时出现问题,在这种情况下我该怎么办?

这是我没有格式化日期时得到的数组

[{"periodo":[{"start":{"date":"2017-06-17 18:20:35.000000","timezone_type":3,"timezone":"UTC"},"current":null,"end":{"date":"2017-06-22 18:20:35.000000","timezone_type":3,"timezone":"UTC"},"interval":{"y":0,`"m":0,"d":1,"h":0,"i":0,"s":0,"weekday":0,"weekday_behavior":0,"first_last_day_of":0,"invert":0,"days":false,"special_type":0,"special_amount":0,"have_weekday_relative":0,"have_special_relative":0},"recurrences":1,"include_start_date":true}
        ,{"start":{"date":"2017-06-17 18:20:35.000000","timezone_type":3,"timezone":"UTC"},"current":null,"end":{"date":"2017-06-22 18:20:35.000000","timezone_type":3,"timezone":"UTC"},"interval":{"y":0,"m":0,"d":1,"h":0,"i":0,"s":0,"weekday":0,"weekday_behavior":0,"first_last_day_of":0,"invert":0,"days":false,"special_type":0,"special_amount":0,"have_weekday_relative":0,"have_special_relative":0},"recurrences":1,"include_start_date":true},{"start":{"date":"2017-06-17 18:20:35.000000","timezone_type":3,"timezone":"UTC"},"current":null,"end":{"date":"2017-06-22 18:20:35.000000","timezone_type":3,"timezone":"UTC"},"interval":{"y":0,"m":0,"d":1,"h":0,"i":0,"s":0,"weekday":0,"weekday_behavior":0,"first_last_day_of":0,"invert":0,"days":false,"special_type":0,"special_amount":0,"have_weekday_relative":0,"have_special_relative":0},"recurrences":1,"include_start_date":true}]}]

*更新

这是我的时间段类的代码

<?php
            namespace App;

            use Illuminate\Database\Eloquent\Model;
            use DateTime;
            use DatePeriod;
            use DateInterval;
            use DB;
            class TimeSlot extends Model
            {
                protected $table = 'timeslots';
                public $timestamps = false;

            function sumarFechas($times) {
                $minutes=0;
                // loop throught all the times
                foreach ($times as $time) {
                    list($hour, $minute) = explode(':', $time);
                    $minutes += $hour * 60;
                    $minutes += $minute;
                }

                $hours = floor($minutes / 60);
                $minutes -= $hours * 60;

                // returns the time already formatted
                return sprintf('%02d:%02d', $hours, $minutes);
            }



            function returnDates($fromdate, $todate) {
                $fromdate =  DateTime::createFromFormat('Y-m-d', $fromdate);
                $todate =  DateTime::createFromFormat('Y-m-d', $todate);
                return new   DatePeriod(
                    $fromdate,
                    new  DateInterval('P1D'),
                    $todate->modify('+1 day')
                );
            }

            function returnDates($fromdate, $todate) {
                $fromdate =  DateTime::createFromFormat('Y-m-d', $fromdate);
                $todate =  DateTime::createFromFormat('Y-m-d', $todate);
                return new   DatePeriod(
                    $fromdate,
                    new  DateInterval('P1D'),
                    $todate->modify('+1 day')
                );
            }


            function getDispo()
            {
                $date=$this->select('slot_date')
                ->where('user_id','=',$this->user_id)
                ->groupBy('slot_date')
                ->get();

                return $date;

            }

            function getHoras()
            {
                $date=$this->select('slot_date','inicio','fin')
                ->where('user_id','=',$this->user_id)
                ->get();

                return $date;

            }

            function getHorasId()
            {
                $date=$this->select('id','slot_date','inicio','fin','slot_status')
                ->where('user_id','=',$this->user_id)
                ->where('slot_date','=',$this->fechaD)
                ->orderBy(DB::raw("STR_TO_DATE(`inicio`, '%l:%i %p')"))
                ->get();

                return $date;

            }

            }

【问题讨论】:

  • $value-&gt;format('Y-m-d'); 中删除-&gt;format('Y-m-d') 时的输出是什么?
  • 嗨@jrn,回复是这样的[[{"date":"2017-06-17 18:09:58.000000","timezone_type":3,"timezone":"UTC"}],{"1":{"date":"2017-06-18 18:09:58.000000","timezone_type":3,"timezone":"UTC"}},{"2":{"date":"2017-06-19 18:09:58.000000","timezone_type":3,"timezone":"UTC"}},{"3":{"date":"2017-06-20 18:09:58.000000","timezone_type":3,"timezone":"UTC"}},{"4":{"date":"2017-06-21 18:09:58.000000","timezone_type":3,"timezone":"UTC"}}]
  • 类Timeslot是什么样的?
  • 嗨@jrn,我已经更新了我的问题
  • Timeslot 类中有两次函数 returnDates()。

标签: php arrays laravel datetime


【解决方案1】:

听起来$value 不是对象DateTime 的实例。 尝试替换此行:

$dates[$m][$key]=$value->format('Y-m-d');//ERROR

这两个:

$timestamp = strtotime($value);
$dates[$m][$key]=date('Y-m-d',$timestamp);//NO ERROR? :-)

你也可以合并成一行:

$dates[$m][$key]=date('Y-m-d',strtotime($value));//NO ERROR? :-)

【讨论】:

  • 更改代码返回错误“日期()预计参数2很长,给定数组”
  • 问题出在变量是一个数组,我试过你告诉我的方法,返回错误,strtotime() expects parameter 1 to be string, array given
【解决方案2】:

在解析之前格式化日期应该可以解决问题

 $value['date'] = date('Y-m-d',strtotime($value['date']));
 $dates[$m][$key]=$value;
//This returns the array with the date formatted

 $dates[$m][$key]=date('Y-m-d',strtotime($value['date']));
//This returns just the formatted dates

【讨论】:

    猜你喜欢
    • 2016-06-06
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    相关资源
    最近更新 更多