I'm having trouble converting timezone's from UTC to a user selected timezone. The problem seems to be Daylight Savings Time.
Here is an example I just coded.
<?php
date_default_timezone_set("UTC");
$timezone = -5.0;
$timestamp = time();
$local_time = $timezone * 3600 + $timestamp;
echo date( "m/d/Y - h:i A", $local_time );
?>
When I run the test file it returns 07/21/2014 - 04:29 PM
. The current time is actually 5:29. The problem is Daylight Savings Time, where our clocks are turned back an hour.
How can I remedy this problem, or is there a more effective method for adjusting timestamps?
Easiest solution I see is making users select whether DST is currently in effect where they live, as not every country/timezone uses DST. If it is in effect then simply modifying the $timezone
variable to +1 would suffice, but would require each user to manage whether DST is in effect or not.
Thank-you in advance.
EDIT:
I tried using DateTime but it was still off...
<?php
$timestamp = time();
echo 'Unix timestamp: ' . $timestamp . "<br/>";
echo 'Unix date: ' . date( "m/d/Y - h:i A", $timestamp ) . "<br/><br/>";
$dt = date_create_from_format('U', $timestamp);
date_timezone_set($dt, new DateTimeZone('America/New_York'));
$adjusted_timestamp = date_format($dt, 'U') + date_offset_get($dt);
echo 'America/New_York: ' . $adjusted_timestamp . "<br/>";
echo 'America/New_York: ' . date( "m/d/Y - h:i A", $adjusted_timestamp );
?>
The results were off by +2 hours. Returns 7:47 PM, it is currently 5:47 PM.
Unix timestamp: 1405979278
Unix date: 07/21/2014 - 11:47 PM
America/New_York: 1405964878
America/New_York: 07/21/2014 - 07:47 PM