Magento日期相关的方法主要在两个文件中。一个是core/date模型类,另外一个是core核心助手类。包含的相关方法如下。
1,core/date,主要的方法就是date,实际上就是简单对PHP中date()函数的封装。定义如下。
/**
* Converts input date into date with timezone offset
* Input date must be in GMT timezone
*
* @param string $format
* @param int|string $input date in GMT timezone
* @return string
*/
public
function
date
(
$format
= null,
$input
= null)
{
if
(
is_null
(
$format
)) {
$format
=
'Y-m-d H:i:s'
;
}
$result
=
date
(
$format
,
$this
->timestamp(
$input
));
return
$result
;
}
使用举例,date()参数为空时,默认参一为Y-m-d H:i:s,参二为当前时间戳。
Mage::getModel(
'core/date'
)->
date
();
//2013-01-09 23:16:10
Mage::getModel(
'core/date'
)->
date
(
'Y-m-d'
);
//2013-01-09
$anyDate
=
'2013-01-09'
;
Mage::getModel(
'core/date'
)->
date
(
'd.m.Y'
,
strtotime
(
$anyDate
));
//09.01.2013
2,核心助手类formatDate方法,该方法定义如下。
/**
* Format date using current locale options and time zone.
*
* @param date|Zend_Date|null $date
* @param string $format See Mage_Core_Model_Locale::FORMAT_TYPE_* constants
* @param bool $showTime Whether to include time
* @return string
*/
public
function
formatDate(
$date
= null,
$format
= Mage_Core_Model_Locale::FORMAT_TYPE_SHORT,
$showTime
= false)
{
if
(!in_array(
$format
,
$this
->_allowedFormats, true)) {
return
$date
;
}
if
(!(
$date
instanceof
Zend_Date) &&
$date
&& !
strtotime
(
$date
)) {
return
''
;
}
if
(
is_null
(
$date
)) {
$date
= Mage::app()->getLocale()->
date
(Mage::getSingleton(
'core/date'
)->gmtTimestamp(), null, null);
}
else
if
(!
$date
instanceof
Zend_Date) {
$date
= Mage::app()->getLocale()->
date
(
strtotime
(
$date
), null, null);
}
if
(
$showTime
) {
$format
= Mage::app()->getLocale()->getDateTimeFormat(
$format
);
}
else
{
$format
= Mage::app()->getLocale()->getDateFormat(
$format
);
}
return
$date
->toString(
$format
);
}
实例演示,参数二支持4个参数,如下所示,参数三为true时,则输出包含当前时间。