Reputation: 1137
The default timezone for my server and MySQL database is set to GMT. My PHP code converts dates that are displayed to the user's local timezone (Eastern in this case):
$OPENED_DATE = '2013-03-20 21:05:00'
$OPENED_DATE = new DateTime($OPENED_DATE);
$OPENED_DATE->setTimeZone(new DateTimeZone('America/New_York'));
Then I output the date for the user:
$OPENED_DATE = strtotime($OPENED_DATE->format('Y-m-d H:i:s'));
$OPENED_DATE = date('F j, Y g:i A T', $OPENED_DATE);
Output of $OPENED_DATE: March 20, 2013 5:05PM GMT
The actual time is displayed correctly but the 'T' in the date output is still displaying GMT. Is there a way to make it display the timezone we've converted to and not the default of GMT. The only way I know to do this is to use date_default_timezone_set
every time to switch to the user's timezone then switch back to GMT. But I feel like there has to be a more efficient way...
Thank you!
Upvotes: 2
Views: 772
Reputation: 117313
Since you applied the timezone setting only to your $OPENED_DATE
variable, the strtotime()
and date()
functions do not receive the same timezone information.
You are passing only the year/month/day/hour/minute/section from your $OPENED_DATE
to strtotime()
, so there is no way for it to get the timezone information.
Now, what you could do is set the default timezone used for functions like strtotime()
and date()
as well, using date_default_timezone_set()
.
However, this is still cumbersome and you don't need to, since already have a DateTime object and you may as well continue to use that.
DateTime objects will let you output a formatted time directly:
$OPENED_DATE->format('F j, Y g:i A T');
Thus skipping the strtotime()
and date()
step entirely.
Upvotes: 1
Reputation: 69927
These two lines are redundant
$OPENED_DATE = strtotime($OPENED_DATE->format('Y-m-d H:i:s'));
$OPENED_DATE = date('F j, Y g:i A T', $OPENED_DATE);
It is the call to date()
which is outputting the wrong timezone.
Why not try just:
$OPENED_DATE = $OPENED_DATE->format('F j, Y g:i A T');
The DateTime
object has the timezone set in it, but once you convert it to a timestamp and use date()
, the server timezone is used for that time. I think just using the DateTime object for formatting the date is sufficient to do what you want.
Upvotes: 1