【问题标题】:laravel Carbon calculate age at death (not till now)laravel Carbon 计算死亡年龄(直到现在)
【发布时间】:2018-05-31 05:02:58
【问题描述】:

get age until now() 可以使用下面的代码

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

但是如果人死了呢?

在数据库 [death_date] 字段中存储 null 或 yyyy-mm-dd

那么如何计算出生日期~死亡日期之间的年龄

// Accessor for Age.
public function getAgeAttribute()
{
    if (!is_null($this->attributes['death_date']))
    {
        // how to calculate death_date - birth_date = realAge
        return $realAge;
    }

    return Carbon::parse($this->attributes['birth_date'])->age;
}

以防万一有人看到这篇文章,这是我的答案

// Accessor for Age.
public function getAgeAttribute()
{
    // return is_null($this->attributes['death_date'])
    //     ? Carbon::parse($this->attributes['birth_date'])->age
    //     : Carbon::parse($this->attributes['birth_date'])->diff(Carbon::parse($this->attributes['death_date']))->format('%y');

    // oh, Carbon will auto convert NULL to now(), so no need the upper code
    return Carbon::parse($this->attributes['birth_date'])->diff(Carbon::parse($this->attributes['death_date']))->format('%y');
}

【问题讨论】:

标签: laravel php-carbon


【解决方案1】:

你可以这样解决:

public function getAgeAttribute()
 {
 if (!is_null($this->attributes['death_date']))
 {
     $realAge = Carbon::parse($this->attributes['death_date'])->diff(Carbon::parse($this->attributes['birth_date']))->format('%y');
      return $realAge
  }

 return Carbon::parse($this->attributes['birth_date'])->age;
}

【讨论】:

    【解决方案2】:
    $birth_date = Carbon::parse($this->attributes['birth_date']);
    $death_date = Carbon::parse($this->attributes['death_date']);
    
    echo $birth_date->diffInYears($death_date);  
    

    【讨论】:

      【解决方案3】:

      假设你正在寻找年龄,试试这个:

      $birth = new Carbon($this->attributes['birth_date']);
      $death = new Carbon($this->attributes['death_date']);
      
      $age = $birth->diffInYears($death); // Returns Integer 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-26
        • 1970-01-01
        • 2020-12-28
        • 2016-03-20
        • 2011-04-16
        • 1970-01-01
        相关资源
        最近更新 更多