Reputation: 116
I have this $date
array:
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
)
)
I want to echo the start date value in timestamp format (2013-09-19 00:00:00)
I tried echo $date['start']->date->getTimestamp();
but it returns me this error : Fatal error: Call to a member function getTimestamp() on a non-object in ...
Upvotes: 0
Views: 2717
Reputation: 76395
You're looking for:
echo $date['start']->format('Y-m-d H:i:s');
I believe... Check all possible formats here, on the manual page
Don't let the dump fool you, the DateTime
object hasn't got a public date
property, as you can see here. It does, however, have a getTimestamp
method, which returns an int, just like time()
does, cf the manual.
You can use any of the predefined constants (all strings, representing standard formats), for example:
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
note: I based the +01:00 and GMT on your dump, showing London as your timezone...
So:
$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');
Read the manual, play around with it for a while, and you'll soon find the DateTime
class, and all of it's related classes (like DateInterval
, DateTimeImmutable
and such (full list here)) are very handy things indeed...
I've put together a little codepad as an example, here's the code:
$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;
Upvotes: 3