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.

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.