PHP

Display DateTime Object In Twig

If you try to display a DateTime object in Twig you will get an error that Twig can not treat the DateTime object as a string.

<p>{{ person.dateOfBirth }}</p>

There are two ways you can get around this problem the first is either within the PHP or you can use Twig filters.

Twig Filter

Twig filters are very useful to convert the values of a variable in twig, allowing you to either convert string to uppercase, lowercase, returning the length of a string...etc. There are loads of default filters you can use in twig.

Here is a list of the default filters

Twig Filters

The filter that we are going to use on the DateTime object is the date filter. This filter will convert your DateTime object into a string taking in a parameter of the format you want to display the date in.

<p>{{ person.dateOfBirth|date('d-m-Y') }}</p>

Extending DateTime Object

The second option is to use your own class for the DateTime object instead of the default PHP DateTime object. Once you have extended this object you are able to create your own method of __toString() and apply the formatting to display the object in here.

The __toString() method will run when PHP trys to treat an object as a string, for example if you had an object and tried to echo the object you will get a can not convert object to string.

// This will error
$date = new \DateTime();
echo $date;

To use the __toString() method you need to create your own class to extend DateTime.

class YourDateTime extends \DateTime
{

}

Now you can create your own __toString method.

class YourDateTime extends \DateTime
{
    public function __toString()
    {
        return $this->format('d-m-Y');
    }
}

If you were to echo this object PHP sees it has a __toString method and will run this instead.

$date = new \YourDateTime();

// This will echo the current date in the format of d-m-Y
echo $date;

With this object in twig we just need to echo it the same way you would in any other way in twig without the error or the Twig filter.

<p>{{ person.dateOfBirth }}</p>
Back to top

Learn how to code with Treehouse

  • Learn projects with access to 1000+ videos
  • Practice live with our Code Challenge Engine
  • Get help in our members-only forums

Start with a 7 day free trial