laravel 5+ 中的年龄计算错误?

Age Calculation error in laravel 5+?

控制器

static function show()
{
    //
    $output = '';
    $result = DB::table('PersonalDetail')
            ->get();
    foreach ($result as $key ) {
        $dob = Carbon::$key->DOB;

        // We need to compare the user's date of birth with today's date.
        $now =Carbon::now();

        // Calculate the time difference between the two dates.
        $difference = $now->diff($dob);

        // Get the difference in years, as we are looking for the user's age.
        $age = $difference->y;

        $output .= '<p>Age:-'.$age.' </p>';
    }

    return ($output);
}

查看Blade

在字符串上调用成员函数 diff()(视图:/Applications/XAMPP/xamppfiles/htdocs/WedLaravel/WedLara/resources/views/pages/ViewPeo.blade.php)

我遇到了这个错误,我已经尝试了很多

要使用 Carbon 计算日期差异,您必须将两个日期都转换为 Carbon 对象,然后使用提供的方法:

$now = Carbon::now();
$dob = Carbon::createFromFormat('Y-m-d', $key->dob);
$diff = $now->diff($dob);

然后您将拥有一个 DateInterval 对象,它会为您提供不同的时间间隔,因此您可以使用 $d->y。由于它是 Carbon,因此您可以使用其他方法,例如

$now->diffInDays($dob);
$now->diffForHumans($dob);