Saving and displaying dates in Magento

There are a few things to be aware of when saving dates in Magento. Magento comes built in with a lot of tools that allow you to work with dates, learning to use these tools will help you improve the consistency and quality of your Magento code as well as increasing your Magento skills. In this post we will only focus on saving dates in the database and then displaying them in a template.

Saving datetime in database

We are going to assume that you already know how to create a new model and database table for the model. Core Magento is programmed to save all datetimes in the database in GMT time, so that is what we are going to do. Here is an easy way to do that correctly:

First, you need to make sure all of the dates are converted to Magento’s internal format as specified in

Varien_Date::DATETIME_INTERNAL_FORMAT

An easy way to do that is to use the

_filterDateTime()

function in the

Mage_Core_Controller_Varien_Action

class (the class should already be inherited by your controller so you can use “$this”). Here is an example using dates submitted by a form:

$params = $this->getRequest()->getParams();

$params = $this->_filterDateTime($params, array('date','date2','date3'));

Once you have formated the datetime, you will need to convert it to GMT like this:

$date = Mage::getModel('core/date')->gmtDate('Y-m-d H:i:s',$params['date'])

Now that it is properly converted to GMT you can save it in your model:

$model->setDate($date)->save()

Showing datetime in template

Here is how you would use Magento’s built in tools to display a datetime that is saved in GMT:

$this->formatDate($date, Mage_Core_Model_Locale::FORMAT_TYPE_SHORT, true)

The formatDate() function will automatically convert the datetime to whichever timezone the user is in. The code above will output the date followed by the time like this:

01/19/2016 10:42 am

If you don’t need to show the time, then just remove the “true” parameter from the formatDate() function.

There you go! Enjoy Magento’s datetime tools!

Leave a Reply