使用 Laravel 5.2 从 Y-m-d 中存储在数据库中的日期计算年龄

Calculate Age from date stored in database in Y-m-d using Laravel 5.2

嗨,用户通过存储在数据库中的表单添加他们的 DOB,

我想根据数据库中存储的日期计算年龄,格式为 Y-m-d,

我的问题是:

这是控制器:

public function index()   {   
    $profile   = User::find($this->userid())->profiledetailsHasOne;  //This has Dob field                   
    return view('profile.index',['profile' => $profile ]); 
}

这是我的模特:

public function getAge(){
    $this->birthdate->diff($this->attributes['dob'])
    ->format('%y years, %m months and %d days');
}

这是我的观点:

<tr>
    <th>Age</th>
    <td>{{$profile->getAge()}}</td>
</tr>

这样对吗?我收到如下错误

Call to a member function diff() on null

计算 Laravel 中的年龄最好使用 Carbon 中的构建来完成。 Laravel 中返回的日期已经是 Carbon 格式。

此逻辑应作为您模型的默认值 getter 放入模型中。

public function getAge(){
    $this->birthdate->diff(Carbon::now())
         ->format('%y years, %m months and %d days');
}

这将导致“23 年 6 个月零 26 天”

查看 http://carbon.nesbot.com/docs/ 文档,了解您可以用它做的所有有趣的事情。

假设您在视图中使用模型,并且您应该在该模型中创建一个 getAge() 函数。

您可以在视图中将您的模型称为 $user->getAge()

谢谢你的建议。

这对碳来说既简单又了不起。

我在模型中添加了这段代码:

public function age() {
return $this->dob->diffInYears(\Carbon::now());
 }

我还设法将日期格式 'Y-m-d' 从数据库更改为此 'd-m-Y' 视图中的传递日期。

我将这段代码放在模型中

public function getDOB(){ 
return $this->dob->format('d-m-Y'); 
 }

日期可以是 Carbon 的实例,它提供了各种有用的方法。

在您的模型中,导入 Carbon class:

use Carbon\Carbon;

并定义一个访问器:

/**
 * Accessor for Age.
 */
public function age()
{
    return Carbon::parse($this->attributes['birthdate'])->age;
}

然后您可以像调用常规属性一样调用 age。例如在 blade 视图中:

<p>{{ $user->age() }} years</p>

直接在您的视图中显示:

\Carbon\Carbon::parse($user->birth)->diff(\Carbon\Carbon::now())->format('%y years, %m months and %d days');
use App\User;
use Carbon\Carbon;

Route::get('/userage',function(){

    $user_info = User::find(1);
    // When  ( $table->date('birthday'); ) 
    $birthday = $user_info->birthday;
    $user_age = Carbon::parse($birthday)->diff(Carbon::now())->format('%y years, %m months and %d days');

    echo($user_age); 
});

我在我的模型中添加了这段代码:

protected $appends = ['age'];

public function getAgeAttribute()
{
   return Carbon::parse($this->attributes['birthday'])->age;
}

在您的 blade 模板中执行此操作

@php
    $birthday = $user->date_of_birth;
    $age = Carbon\Carbon::parse($birthday)->diff(Carbon\Carbon::now())->format('%y years, %m months and %d days');
@endphp

        <p>{{$age}}</p>

在 User.php 模型在 Laravel:
添加了这个功能

public function getAge() {
    $format = '%y years, %m months and %d days';
    return \Carbon\Carbon::parse(auth()->user()->dateofbirth)->diff(\Carbon\Carbon::now())->format($format);
}

在视图中 Blade:

Age: {{ auth()->user()->getAge() }}

在laravel 7中:

$dateOfBirth = '1990-01-01';
$years = \Carbon::parse($dateOfBirth)->age;
  
dd($years); // 31