Magento1.8 – Date Behaves Differently in Column and Form Field

adminformdatemagento-1.8

Date stored in database: 2014-02-07 00:00:00

Magento Timezone: IST (GMT +5.30)

When I display this in column – it displays – 2014-02-07 05:30:00 which is correct and expected (since magento stores dates in UTC).

However, when I try to display the same date in textbox (readonly), it displays 2014-02-07 00:00:00 i.e. exactly same as in database – without any conversion.

How can I convert the date to show correct value in textbox?


$fieldset->addField('end_date', 'date', array(
'label' => Mage::helper('survey')->__('End Date'),
'index' => 'end_date',
'name' => 'end_date',
'class' => 'readonly',
'readonly' => true,
'format' => Mage::app()->getLocale()->getDateTimeFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT),
));

Best Answer

I'm not sure if this is the best solution, but I think it should work:

Add a custom renderer to the textfield that will format the date:

$renderer = $this->getLayout()->createBlock('foo/widget_grid_renderer_date');
$fieldset->addField('end_date', 'text', array(
            'label'     => Mage::helper('survey')->__('End Date'),
            'index'     => 'end_date',
            'name'      => 'end_date',
            'class'     => 'readonly',
            'readonly'  => true
      )
    )->setRenderer($renderer);

Create a new renderer class:

class Example_Foo_Block_Widget_Grid_Renderer_Date extends Mage_Adminhtml_Block_Template 
    implements Varien_Data_Form_Element_Renderer_Interface
{

    public function render() {

        //...
        return Mage::getSingleton('core/locale')
                        ->date($data, Zend_Date::ISO_8601, null, false)->toString($format);     
    }
}