Zend Framework 2: formatting a date in a view

2019-04-17 06:10发布

I'm new to Zend framework and have decided to try to build a simple app using ZF2.

I have a date that is being pulled from the database where my table gateway extends the AbstractTableGateway, this is pulling my data correctly but i'd like to format my date using Zend_Date and not manipulate the string representation myself in my model / view.

Does anybody have any ideas about how i do this?

2条回答
贪生不怕死
2楼-- · 2019-04-17 06:36

Here is my custom datatime helper for reference:

https://github.com/AlloVince/eva-engine/blob/master/vendor/Eva/View/Helper/Datetime.php

register this helper as a invokable helper service in your module config file

'view_helpers' => array(
    'invokables' => array(
        'datetime' => 'Eva\View\Helper\Datetime',
    ),  
),

Then call it in view by:

$this->datetime(time(), 0, 'Y-m-d');  //2012-10-09
$this->datetime()->jsTime(time()); //Sat Oct 6 17:16:05 UTC+0800 2012
查看更多
趁早两清
3楼-- · 2019-04-17 06:48

Another option would be the already present ViewHelper \Zend\I18n\View\Helper\DateFormat

This way you could ensure that your view-scripts are ready for internationalization (i18n) and that all your page viewers would be able to see the date in their respective formats.

This requires the php_intl extension to be enabled.

The long usage would look something like the following:

echo $this->dateFormat(
    new DateTime(),
    IntlDateFormatter::MEDIUM, // date
    IntlDateFormatter::MEDIUM, // time
    "en_US"
);

However, just like AlloVince's approach, i would suggest writing your own view-helper for that. This way you could write something like $this->myDateFormat($db->getDate())

查看更多
登录 后发表回答