Lal Mohan
Lal Mohan

Reputation: 323

how to display mongodb date in symfony2 twig template?

I have a website listing products using symfony2 and mongodb

I added the items into mongodb with create date and need to display all items in my twig template.

For this

In my controller I passed the array itemlist to twig template.

My twig template

{% for item in itemlist %}
<h4>{{item.name}}</h4>
<p>{{item.name}}</p>
{{item.createdate}}
{% endfor %}

Here I am not getting the item.createdate

How to directly display the mongo date in twig template?

is there any twig extension for this?

Upvotes: 2

Views: 1590

Answers (4)

Kaliseo
Kaliseo

Reputation: 21

Th most simple way i found is :

{{ event.begin.toDateTime()|date("d/m/Y H:i:s") }}

Upvotes: 0

webDEVILopers
webDEVILopers

Reputation: 1916

I've experienced problems with timezones using sec. Instead I used toDateTime which works fine.

{{ sampleDate.toDateTime|date('Y-m-d') }} 

MongoDate::toDateTime

Upvotes: 1

user3873619
user3873619

Reputation: 371

{{ sampleDate.sec|date('Y-m-d') }} 

Upvotes: 4

sebbo
sebbo

Reputation: 2939

This is an extension class that might work for you:

class MongoDateExtension extends \Twig_Extension
{
    /**
     * @inheritdoc
     */
    public function getName()
    {
        return 'mongoDate_extension';
    }

    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('convertMongoDate', array($this, 'convertMongoDateFilter')),
        );
    }

    public function convertMongoDateFilter(\MongoDate $mongoDate)
    {
        return new \DateTime('@' . $mongoDate->sec);
    }
}

Then register the class to your dependency injection container by adding the following snippet to your services.xml. Consider that you have to adjust the class path in the example.

<service id="twig.extension.mongo_date"
         class="Path\To\Your\Bundle\Twig\Extension\MongoDateExtension">
    <tag name="twig.extension"/>
</service>

The extension will convert the mongo date to a php \DateTime object. It will perform the transformation with an accuracy of seconds so if you need microseconds as well you will need to adjust the extension.

Finally in your twig template you can just use the twig date formatting extension:

{{ sampleDate|convertMongoDate|date('Y-m-d') }} 

which will print 2013-11-05

Upvotes: 1

Related Questions