Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@herveguetin
Created May 28, 2014 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save herveguetin/2d1c6a9dfd00cf759f46 to your computer and use it in GitHub Desktop.
Save herveguetin/2d1c6a9dfd00cf759f46 to your computer and use it in GitHub Desktop.
Properly manage dates and datetimes in admin form (displaying and saving data in order to make sure to fit to locale in Magento)
<?php
/**
* 1) Make sure to display a correct date or datetime input field in admin forms
*
* Code below is in a _prepareForm() method of an admin form
*/
$dateOutputFormat = Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
$fieldset->addField('my_date_field', 'date', array(
'name' => 'my_date_field',
'label' => $this->__('My Date Field'),
'title' => $this->__('My Date Field'),
'image' => $this->getSkinUrl('images/grid-cal.gif'),
'format' => $dateOutputFormat,
));
$datetimeOutputFormat = Mage::app()->getLocale()->getDateTimeFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
$fieldset->addField('my_datetime_field', 'date', array( // Yes, input type is 'date'
'name' => 'my_datetime_field',
'label' => $this->__('My Datetime Field'),
'title' => $this->__('My Datetime Field'),
'image' => $this->getSkinUrl('images/grid-cal.gif'),
'format' => $datetimeOutputFormat,
'time' => true,
));
/**
* 2) Make sure to save data in a correct DATETIME format in DB
*
* Code below is in the save action of the controller in charge of saving form data
*/
$formData = array(); // Your logic to get posted form data as array
$data = $this->_filterDates($data, array('my_date_field')); // all date fields in array
$data = $this->_filterDateTime($data, array('my_datetime_field')); // all datetime fields in array
@vaseemansari007
Copy link

I have done the same explained above but don't know why the datetime is not getting saved in db.

while debugging i can see the value [from_date] => 2015-09-10 02:02:00 but it is not saving in db. My db field from_date is
from_date DATETIME NOT NULL,
I am trying this in MCE 1.7. do u have any idea, how to save datetime in db.

@alvinnguyen
Copy link

This doesn't seem to take timezone into account. Maybe I missed something.

@waynetheisinger
Copy link

line 32 and 33 are not both needed

  • if you want to keep the timezone use $data = $this->_filterDateTime($data, array('my_datetime_field'));
  • if you don't then use $data = $this->_filterDates($data, array('my_date_field'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment