magento 时间处理 Playing with Dates in Magento

Introduction

Being a PHP developer, you are no way hiding from PHP’s date() function.


In case of Magento, makes an usage of timezone which is configured from the backend (System > Configuration > General > Locale Options > Timezone ) for formatting/displaying date/time.


And this makes the results obtained with the php’s solely date() function and the Magento’s one a bit different.


For example:


Normal PHP Way

$currentTimestamp = time();
echo $date = date('Y-m-d', $currentTimestamp); //2011-12-11 (current date of the server)
 

Magento Way

$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.
 

Since Magento is meant to be for multi-website / multi-lingual / multi-locale purpose, it’s always a good practice to format the date using Magento’s date/time function.


AFAIK, there is no need for conversion of date/time while inserting into the database. The formatting/conversion thing is only done at the frontend level for displaying purposes.


Some Useful Examples

1. Displaying current date

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

OR

echo $currentDate = Mage::getModel('core/date')->date('Y-m-d');
 

2. Formatting any date in any format

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

OR

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

3. Predefined date formatting

$dateToFormat = '2011-12-11';
Mage::helper('core')->formatDate($dateToFormat, 'medium', false);
 

Note: Mage_Core_Helper_Data::format() has following arguments

/**
 * 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)
{
....
}
 

Hope this gave some info about Date/Time functionality available in Magento.
Thanks for reading!
Cheers!!

 

来源:  http://www.blog.magepsycho.com/playing-with-dates-in-magento/

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值