【问题标题】:How to show the current age in months using twig, symfony2?如何使用 twig、symfony2 以月为单位显示当前年龄?
【发布时间】:2017-04-24 13:17:44
【问题描述】:

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

<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>

有什么想法吗?

【问题讨论】:

  • 如果你想得到总月数,你可以像这样{# entity.birthdate is string or DateTime objects #} {% set difference = date('now').diff(date(entity.birthdate)) %} {% set months = difference.format('Y')*12 + difference.format('m') %} smt 如果你把剩余天数计算到一个月,你必须检查,如果天大于 1,然后加 1到几个月

标签: php symfony date twig


【解决方案1】:

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

我想显示婴儿的年龄是您将来可能再次需要的东西,所以让我们将其作为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

【讨论】:

  • 谢谢,很有用
猜你喜欢
  • 1970-01-01
  • 2016-01-25
  • 1970-01-01
  • 1970-01-01
  • 2015-05-21
  • 1970-01-01
  • 2011-08-16
  • 2011-06-10
  • 2014-08-06
相关资源
最近更新 更多