DateTime ParamConverter in Symfony controller

DateTime ParamConverter in Symfony controller

Param converters are a very useful feature in Symfony when working with controllers. The default setup does not support dates to be converted. But Sensio does.

By installing the sensio/framework-extra-bundle with composer require sensio/framework-extra-bundle you also have a param converter for dates. If you use Symfony flex, it's even easier. Simply run composer require annotations.

This way you're able to use the following:

/**
 * @Route("/my/{date}")
 */
public function myAction(\DateTime $date): Response
{
    ...
}

And as you're most likely want to define the format of the date which is provided via the routing, you can also do this:

/**
 * @Route("/my/{date}")
 * @ParamConverter("date", options={"format": "Y-m-d"})
 */
public function myAction(\DateTime $date)
{
    ...
}