php - 如何使用 twig, symfony2 以月为单位显示当前年龄?

标签 php symfony date twig

我有一个项目,我想以月为单位显示婴儿的当前年龄,还有一个代码可以计算和显示以年为单位的年龄,但我想要以月为单位。这是 mi 代码。

<td>{% if entity.birthdate %}{{ ('now'|date('Y') - entity.birthdate|date('Y') - 1) + ('now'|date('Y-m-d')|date('U') - entity.birthdate|date('Y-m-d')|date('U') >= 0 ? 1 : 0) }}{% endif %}</td>

有什么想法吗?

最佳答案

虽然在模板/ View 中计算值很诱人,但最好将逻辑和表示分开。

我想显示婴儿的年龄是您将来可能再次需要的东西,所以让我们将其作为 entity 的方法(即 entity 的函数)。

// entity.php
class person
{
    // Assumption: $birthdate is a DateTime object.
    protected $birthdate;

    // getAge() outputs something like this: '1 years, 1 months, 8 days old.'
    public function getAge()
    {
        $now = new \DateTime('now');
        $age = $this->getBirthdate();
        $difference = $now->diff($age);

        return $difference->format('%y years, %m months, %d days old.');
    }

    public function getBirthdate()
    {
        return $this->birthdate;
    }

    public function setBirthdate($birthdate)
    {
        $this->birthdate = $birthdate;
        return $this;
    }
}

然后在您的 Twig 文件中,您可以访问 getAge 方法:

{{ entity.age }}

因为我很想知道怎么做,你也可以在 Twig 中做到这一点;)

{{ date('now').diff((date('2014-1-3'))).format('%y years %m months %d days old') }}

Try it on twigFiddle

关于php - 如何使用 twig, symfony2 以月为单位显示当前年龄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41054011/

相关文章:

php - 开始日期和开始时间小于结束日期和结束时间验证

php - jquery 视口(viewport)大小更改 timthumb 输出

php - 如何添加两个数据库列显示结果

php - Symfony3 : How to delete current user and redirect to home?

python - 使用 Python 将包含复杂日期值的字符串转换为日期

ios - 格式化互联网时间字符串(Swift 1.2)

php - 设置多个类来表示真实世界的对象

wordpress - PHP 警告 : POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

validation - Symfony2 UniqueEntity 多个字段 : false positive validation?

php - Symfony2 - Ajax 搜索