Using PHP 5.2.5 I was working with some DateTime objects and noticed a time that seemed off. The problem I'm having may be related to timezones, but I'm not sure - I'm creating a DateTime from a Unix Time Stamp and getting different/unexpected results depending on how I output it.
I created the following to easily illustrate the "issue":
$timezone = new DateTimeZone('America/Chicago');
$now = time();
$now_datetime = new DateTime('@' . $now, $timezone);
echo phpversion() . "\n\n";
echo $now . "\n";
echo $now_datetime->format('U') . "\n\n";
echo date('g:i:sa', $now) . "\n";
echo $now_datetime->format('g:i:sa') . "\n\n";
This outputs the following:
5.2.5
1287676530
1287676530
10:55:30am
3:55:30pm
I'm currently in the correct timezone, and the server shows the "right" time (10am) when using the date()
function to output a formatted date, as well as 'America/Chicago' being the default timezone on that machine. But, when outputting values via DateTime::format()
, the times are very different.
I added the ->format('U')
just to verify that it was holding the correct timestamp.
So, I'm probably doing something wrong or I have the wrong expectations. So what am I missing?
It seems like a timezone issue with DateTime, but if that's the case, why does it show "now" in America/Chicago as ... wrong?