Reputation: 1262
Some of my tables contain date fields and some values are set to: '0000-00-00', when I try to print the date in a twig template like this:
{{ entity.date | date('m/d/Y') }}
I get the following exception:
An exception has been thrown during the rendering of a template ("DateTime::__construct(): Failed
to parse time string (-001-11-30T00:00:00-06:00) at position 7 (-):
Double timezone specification") in MGAdminBundle:Customers/Partials:_estimates.html.twig at line 12.
Upvotes: 1
Views: 2851
Reputation: 1245
The date filter accepts strings (it must be in a format supported by the strtotime function), DateTime instances, enter link description here
You can create a twig extension
<?php
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Bundle\TwigBundle\Loader\FilesystemLoader;
use CG\Core\ClassUtils;
class PostExtension extends \Twig_Extension{
protected $loader;
protected $controller;
public function __construct(FilesystemLoader $loader)
{
$this->loader = $loader;
}
public function setController($controller)
{
$this->controller = $controller;
}
/**
* {@inheritdoc}
*/
public function getFunctions()
{
return array(
'dateFormater' => new \Twig_Function_Method($this, 'dateFormater', array('is_safe' => array('html'))),
);
}
public function dateFormater($dateTime){
$now = new \DateTime('NOW');
return $now->format( 'd-m-Y' ); // any other format !!
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'some_extension';
}
}
now add it as a service !
<services>
<service id="twig.extension.postExtension" class="Project\PostBundle\Twig\Extension\PostExtension" public="false">
<tag name="twig.extension" />
<argument type="service" id="twig.loader" />
</service>
<service id="project.post.listener" class="Project\PostBundle\EventListener\ControllerListener">
<tag name="kernel.event_listener" event="kernel.controller" method="onKernelController" />
<argument type="service" id="twig.extension.postExtension" />
</service>
</services>
so finally you can use it as a filter in your twig code
{{ dateFormater(entity.date) }}
enjoy !
Upvotes: 1