Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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";
share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

Instantiating a DateTime with @ uses no timezone, so you'd have to set the timezone afterwards:

$dateTime = new DateTime("@".$ts);
$dateTime->setTimezone(new DateTimeZone("Pacific/Auckland"));
echo $dateTime->format("h:i:sa d/m/Y");

// 02:51:30pm 08/04/2013
share|improve this answer
    
Thanks Jack. It says it right in the docs there too. I read it and didn't think anything of it as I thought having the default timezone already set to Pacific/Auckland for the rest of the app would handle this. Apparently not. Thanks again. –  JamesNZ Apr 8 '13 at 3:43
    
@James I'm not sure why this design was chosen actually, but it's at least documented ;-) –  Jack Apr 8 '13 at 3:46
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.