使用 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,

我的问题是:

  • 如何计算年龄?

  • 逻辑放在哪里,在控制器还是模型中?

  • 如何以这种格式"m-d-Y"传递视图中存储的日期

  • 如何传递逻辑的结果,这是年龄在视野中。

  • 我在我的模型中使用了下面的东西,对吗?

这是控制器:

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

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

在模型中,导入碳类:

use Carbon'Carbon;

并定义一个访问器:

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

然后,您可以调用age,就好像它是常规属性一样。例如,在边栏选项卡中:

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

要直接显示在视图中,请执行以下操作:

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

我在模型中添加了以下代码:

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

在 laravel 7 中:

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

感谢您的所有建议。

对于碳来说,这很容易而且很棒。

我在模型中添加了以下代码:

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

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

此逻辑应作为模型的默认 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()

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); 
});

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

我把这段代码放在模型中

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

刀片模板中执行此操作

@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);
}

在视图边栏选项卡中:

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