首页 > 解决方案 > 从给定的出生日期计算年龄组

问题描述

在一个应用程序中,我有一个如下所示的选择框:

<select name="AgeGroup" class="form-control" id="AgeGroup">
    <option value="18-24" selected=""18-24</option>
    <option value="18-24">18-24 years</option>
    <option value="25-34">25-34 years</option>
    <option value="35-44">35-44 years</option>
    <option value="45-54">45-54 years</option>
    <option value="55-64">55-64 years</option>
    <option value="65 Plus">65 years or over</option>
    <option value="PTNA">Prefer not to answer</option>
</select>

除此之外,我还询问了用户的出生日期,但同时询问用户似乎很愚蠢,因为您肯定可以从提供的出生日期算出给定的年龄组吗?

当我收集出生日期时,我有一个简单的变异器来获取用户的年龄,如下所示:

/**
 * Calculate the user's age in years given their date of birth
 *
 * @return void
 */
public function getAgeAttribute()
{
    $this->birth_date->diff(Carbon::now())->format('Y');
}

然后我意识到我什至不需要年龄属性来计算年龄组,所以我制作了另一个像这样的访问器:

/**
 * Infer the users age group given their date of birth 
 *
 * @return void
 */
public function getAgeGroupAttribute()
{
    $age = $this->birth_date->diff(Carbon::now())->format('Y');

    switch($age){
        case($age <= 24);
            return "18 - 24";
        break;
        case ($age <= 34);
            return "25 - 34";
        break;
        case ($age <= 44);
            return "35 - 44";
        break;
        case ($age <= 54);
            return "45 - 54";
        break;
        case ($age <= 64);
            return "55 - 64";
        break;
        case ($age > 64);
            return "Over 65";
        break;
        default:
            return "Unspecified age group";
    }
}

但我担心的是,如果他们实际上没有选择提供年龄怎么办?由于此表格带有“不想说”的选项。

我可以先检查一下这实际上是不是一个日期$user->age_group吗?

另外,我想第一个开关盒应该有一个 or 因为你可能小于 18 岁。

像这样:case($age >= 18 && $age <= 24);

标签: phplaravel

解决方案


您可以将不喜欢回答null值存储为他们的出生日期。然后,在检查用户的年龄组时,您可以检查一个null值并在访问器中返回您不喜欢回答或未指定的选项:

public function getAgeGroupAttribute()
{
    if ($this->birth_date === null) {
        return 'Unspecified';
    }

    $age = $this->birth_date->diff(Carbon::now())->format('Y');

    // ...
}

推荐阅读