How to add a date/time input field to your Magento extension

In your extension’s Form.php:

For Example: app/code/local/CompanyName/ModuleName/Block/Adminhtml/ModuleName/Edit/Tab/Form.php

Add the following code:

$dateFormatIso = Mage::app()->getLocale()->getDateTimeFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
$fieldset->addField('start_date', 'date', array(
  'name'   => 'start_date',
  'label'  => Mage::helper('events')->__('Start Date'),
  'title'  => Mage::helper('events')->__('Start Date'),
  'image'  => $this->getSkinUrl('images/grid-cal.gif'),
  'input_format' => $dateFormatIso,
  'format'       => $dateFormatIso,
  'time' => true
));

The key things to make it work are the “input_format”, “format”, and “time” parameters in the addField array. Setting the “time” variable to “true” makes the time input fields appear in the date selector pop-up.

11 Comments

  1. Thank you Axel. I have saved my time

  2. Roger

    Is it possible to specify the timezone for this datetime field?

    • Axel (Author)

      Hi Roger. I don’t believe so. You’ll probably have to extend the date field and create a custom one that allows for defining the timezone within the field.

  3. Hi

    I am doing the same in my _prepareForm() and when the form is posted i can see values – [from_date] => 2015-09-10 02:02:00
    but the values are not getting saved in db.
    My db field is this – `from_date` DATETIME NOT NULL,
    Do u have idea idea what is the issue.

    • Axel (Author)

      Did you create the from_date column in the database yourself?

      If so, be sure you’re deleting everything under your var/cache folder. Magento sometimes caches the database structure for tables and it won’t pick up on new columns unless you flush the cache.

  4. Itunu Daniel

    Is it possible to extend the date of a category in magento without going through the codes.

  5. Itunu Daniel

    i created a sale category and the date i set it to will expire on the 30th of this month.Please how can i extend the date of the sale category without going to individual items to change the date and without using codes.

    • Axel (Author)

      Hi there.

      I would recommend using the Catalog Price Rules to apply a discount to the entire category instead of setting a sale price to each individual item.

      Go under Promotions > Catalog Price Rules and set a rule that applies to your category.

  6. chirag chauhan

    if i need to show time with date picker in the front end, then what to do??

  7. Marcone Ferreira Ramos

    Thank you very much!

  8. Jon

    Very useful post :)
    Thanks :D

Leave a Reply to Axel