Sunday, 21 October 2012

Playing with dates in magento


Introduction

Magento makes an usage of timezone which is configured from the backend (System > Configuration > General > Locale Options > Timezone) for formatting/displaying date/time.
$currentTimestamp = Mage::getModel('core/date')->timestamp(time()); //Magento's timestamp function makes a usage of timezone and converts it to timestamp
echo $date = date('Y-m-d', $currentTimestamp); //The value may differ than above because of the timezone settings.


Some Useful Examples

1. Displaying current date

1
2
$currentTimestamp = Mage::getModel('core/date')->timestamp(time());
echo $currentDate = date('Y-m-d', $currentTimestamp);
OR
1
echo $currentDate = Mage::getModel('core/date')->date('Y-m-d');

2. Formatting any date in any format

1
2
3
$anyDate = '2011-12-11';
$dateTimestamp = Mage::getModel('core/date')->timestamp(strtotime($anyDate));
echo $currentDate = date('d.m.Y', $dateTimestamp);
OR
1
2
$anyDate = '2011-12-11';
echo $currentDate = Mage::getModel('core/date')->date('d.m.Y', strtotime($anyDate));

3. Predefined date formatting

1
2
$dateToFormat = '2011-12-11';
Mage::helper('core')->formatDate($dateToFormat, 'medium', false);
Note: Mage_Core_Helper_Data::format() has following arguments
1
2
3
4
5
6
7
8
9
10
11
12
/**
 * Format date using current locale options
 *
 * @param   date|Zend_Date|null $date in GMT timezone
 * @param   string $format (full, long, medium, short)
 * @param   bool $showTime
 * @return  string
 */
public function formatDate($date=null, $format='short', $showTime=false)
{
....
}

No comments:

Post a Comment