Calculate difference between two dates with timestamps in Laravel

余生颓废 提交于 2021-01-01 19:21:28

问题


I have in my table a timestamps with created_at and updated_at

$table->timestamps();

But I want to add another column that calculates the difference between created_at and updated_at in days

Should I do that in SQL or in my controller?


回答1:


You can do that from within your Eloquent model. Let's assume your model has the name User. You can create a computed field by defining an Accessor.

class User extends Model 
{
  $dates = [
    'updated_at',
    'created_at'
  ];
  $appends = ['diffInDays'];

  public function getDiffInDaysAttribute()
  {
    if (!empty($this->created_at) && !empty($this->updated_at)) {
      return $this->updated_at->diffInDays($this->created_at);
    }
  }
}

Some explanation

By adding created_at and updated_at to the $dates array, Laravel automatically casts your date values to Carbon. Now, if you do something like $user->created_at, you don't get the string, but a Carbon instance of that date. This allows you to make some nice date calculations, like the one above.

By adding an Accessor with the getDiffInDaysAttribute function, you can call the days difference via $user->diffInDays like a normal attribute, although it is not on the model.

But if you would now do something like $user->toArray(), the diffInDays attribute will not be available. To always add the difference in days when you retrieve User data, you can add the field to the $appends array. That way, the field will always be returned when you retrieve User data via Eloquent.




回答2:


To have it auto save this value on every update to that model, then you can put this in the model.

public static function boot() 
{
    parent::boot();

    static::updating(function($model) {
        $diffInDays = $model->updated_at->diffInDays($model->created_at);
        $model->timestamp_difference = $diffInDays;
    });
}

timestamp_difference is the name of the DB column that I used, this can be whatever you want it to be.




回答3:


Use Carbon for count date difference in days.

   $to = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $created_at);
   $from = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $updated_at);
   $diff_in_days = $to->diffInDays($from);


来源:https://stackoverflow.com/questions/58957324/calculate-difference-between-two-dates-with-timestamps-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!