我有这个$date
数组:
Array
(
[start] => DateTime Object
(
[date] => 2013-09-19 00:00:00
[timezone_type] => 3
[timezone] => Europe/London
)
[end] => DateTime Object
(
[date] => 2013-10-20 23:59:00
[timezone_type] => 3
[timezone] => Europe/London
)
)
我想以时间戳格式回显开始日期值(2013-09-19 00:00:00)
我尝试了echo $date['start']->date->getTimestamp();
,但它返回了我的错误:Fatal error: Call to a member function getTimestamp() on a non-object in ...
答案 0 :(得分:3)
您正在寻找:
echo $date['start']->format('Y-m-d H:i:s');
我相信......检查所有可能的格式here, on the manual page
不要让转储欺骗你,DateTime
对象没有公共date
属性,as you can see here。但是,它有一个getTimestamp
方法,它返回一个int,就像time()
一样,cf the manual。
您可以使用任何预定义常量(所有字符串,表示标准格式),例如:
echo $data['end']->format(DateTime::W3C);//echoes Y-m-dTH:i:s+01:00)
//or, a cookie-formatted time:
echo $data['end']->format(DateTime::COOKIE);//Wednesday, 02-Oct-13 12:42:01 GMT
注意:我在您的转储中基于 +01:00 和 GMT ,将伦敦显示为您的时区......
所以:
$now = new DateTime;
$timestamp = time();
echo $now->getTimetamp(), ' ~= ', $now;//give or take, it might be 1 second less
echo $now->format('c'), ' or ', $now->format('Y-m-d H:i:s');
阅读手册,暂时使用它,您很快就会找到DateTime
课程及其所有相关课程(例如DateInterval
,DateTimeImmutable
等(full list here))确实非常方便......
我把一个小codepad放在一起作为例子,这是代码:
$date = new DateTime('now', new DateTimeZone('Europe/London'));
$now = time();
if (!method_exists($date, 'getTimestamp'))
{//codepad runs <PHP5.3, so getTimestamp method isn't implemented
class MyDate extends DateTime
{//bad practice, extending core objects, but just as an example:
const MY_DATE_FORMAT = 'Y-m-d H:i:s';
const MY_DATE_TIMESTAMP = 'U';
public function __construct(DateTime $date)
{
parent::__construct($date->format(self::MY_DATE_FORMAT), $date->getTimezone());
}
/**
* Add getTimestamp method, for >5.3
* @return int
**/
public function getTimestamp()
{//immediatly go to parent, don't use child format method (faster)
return (int) parent::format(self::MY_DATE_TIMESTAMP);
}
/**
* override format method, sets default value for format
* @return string
**/
public function format($format = self::MY_FORMAT)
{//just as an example, have a default format
return parent::format($format);
}
}
$date = new MyDate($date);
}
echo $date->format(DateTime::W3C), PHP_EOL
,$date->format(DateTime::COOKIE), PHP_EOL
,$date->getTimestamp(), ' ~= ', $now;