I use php DateTime all the time and I've just done some work on an older app that uses date() for everything. I noticed my DateTime times weren't matching up with the date() times. This has me fairly concerned.
I ended up doing some testing locally and found DateTime is giving incorrect results on my local machine when instantiating with a unix timestamp (in the format "@1365389490"). They're 12 hours behind (or more depending on daylight savings).
Please note I've tested these in my MAMP Pro installation using php 5.2.17, 5.3.14 and 5.4.4 (and yes I restarted apache before each attempt). I've also tested on a development server on php 5.3.6. All of them output the wrong values.
# To confirm date() uses the right timezone
date_default_timezone_set("Pacific/Auckland");
$ts = '1365389490'; # 02:51:30pm 08/04/2013
# This shows correctly (02:51:30pm 08/04/2013)
echo date("h:i:sa d/m/Y", $ts) . "<br /><br />";
# This shows incorrectly (02:51:30am 08/04/2013)
$dateTime = new DateTime("@".$ts, new DateTimeZone("Pacific/Auckland"));
echo $dateTime->format("h:i:sa d/m/Y");
Strangely this alternate way works. This is the old PHP 5.2 and earlier method.
$dateTime = new DateTime();
$dateTime->setTimestamp($ts);
echo $dateTime->format("h:i:sa d/m/Y");
This is basic stuff. I'm at a loss as to why it's not behaving itself. Any help would be much appreciated.
Resolved
As per the php docs, the timezone is disregarded when you pass a timezone to the DateTime constructor. The times were coming out as UTC for me (despite my app timezone being set to Pacific/Auckland).
From the docs: http://php.net/manual/en/datetime.construct.php
// Using a UNIX timestamp. Notice the result is in the UTC time zone.
$date = new DateTime('@946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";