簡體   English   中英

如何使用細枝symfony2顯示當前月份的年齡?

[英]How to show the current age in months using twig, symfony2?

我有一個項目,希望以月為單位顯示當前嬰兒的年齡,也有一個代碼以年為單位顯示並顯示年齡,但是我想以幾個月為單位。 這是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>

有什么想法嗎?

盡管很想在模板/視圖中計算值,但最好將邏輯和表示法分開。

我想顯示嬰兒的年齡是將來您可能想要的,因此讓我們將其作為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') }}

在twigFiddle上嘗試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM