【发布时间】: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');
}
【问题讨论】:
-
@ali 和 Oscar A Garcia 和 climon 使用相同的计算,但我更喜欢 ali 的答案,谢谢大家
标签: laravel php-carbon