twig tutorial - Simple Date of Birth to age filter in Twig - twig date format - twig php - twig template



Simple Date of Birth to age filter - twig date format

How to ...

1 - use twig extension class that extends

use \Twig_Extension

class dobToAge extends \Twig_Extension {

2 - Add the appropriate filter by overriding getFilters() method

public function getFilters() {
        return array(
            'age' => new \Twig_Filter_Method($this, 'getAge'),
        );
 }

3 - Add some logic to get the age of a given Date of Birth

public function getAge($date) 
     {
        if (!$date instanceof \DateTime) {
        // turn $date into a valid \DateTime object or let return
        return null;
         }

     $referenceDate = date('01-01-Y');
     $referenceDateTimeObject = new \DateTime($referenceDate);
     $diff = $referenceDateTimeObject->diff($date);
     return $diff->y;
    }
}

Then, call your filter as follow,

{{ yourDateOfBirthInstance | age }}

Related Searches to twig tutorial - Simple Date of Birth to age filter in Twig