简体   繁体   中英

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

I have a project where I want to display the current age of an infant in months, also have a code that calculates and displays the age in years, but I want to have it in months. This is mi code.

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

Any idea please?

Although it's tempting to compute values in templates/views, it's best to separate logic and presentation.

I imagine that displaying a baby's age is something that you might want again in the future, so let's make it a method on the entity (ie a function of the entity class ).

// 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;
    }
}

Then in your Twig file you can access the getAge method:

{{ entity.age }}

Because I was interesting in knowing how, you can also do this in Twig ;)

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

Try it on twigFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM