DateTime :: __ construct()期望参数1是字符串,给定对象

DateTime :: __ construct()期望参数1是字符串,给定对象

问题描述:

I am trying to get two date calculation . when i placed

$from = Carbon::createFromFormat('m-d-Y H:i:s', '02-10-2017 10:02:20');

code i get value but when i placed data from mysql

$from = Carbon::createFromFormat('m-d-Y H:i:s', $from_date); 

can not find data, and can not calculation to and from date

Controller.php

public function circulerMatchView()
    {
        $user_id = Auth::user()->id;

        $resume_exp = Experience::select('user_exp_keyword')
                    ->where('user_id','=',$user_id)
                    ->get();
        $from_date = Experience::selectRaw('exp_from_date')
                    ->where('user_id','=',$user_id)
                    ->orderBy('exp_from_date','desc')
                    ->take(1)
                    ->get();
        $to_date = Experience::selectRaw('exp_to_date')
                    ->where('user_id','=',$user_id)
                    ->orderBy('exp_from_date','desc')
                    ->take(1)
                    ->get();

             $from = DateTime::createFromFormat('m-d-Y H:i:s', $from_date);
             $to = Carbon::createFromFormat('m-d-Y H:i:s', $to_date);
            $realAge = Carbon::parse($to)->diff(Carbon::parse($from))->format('%y');   
            print_r($realAge);
}

if $from_date is 02-21-2017 and $to_date is 02-21-2018

result is 1 year

You are fetching array by using get. Replace these two lines with your codes and check. It will fetch only field data values.

$from_date = Experience::
                    where('user_id','=',$user_id)
                    ->orderBy('exp_from_date','desc')
                    ->take(1)
                    ->pluck('exp_from_date')[0];
$to_date = Experience::
                where('user_id','=',$user_id)
                ->orderBy('exp_to_date','desc')
                ->take(1)
                ->pluck('exp_to_date')[0];

Once check this documentation for details about pluck.