This is a follow up question on my previous one. The app is javascript/php. In Javascript, I'm getting the local timestamp and timezone offset:
var timestamp = new Date().getTime();
var tzoffset = new Date().getTimezoneOffset();
I am testing this from London and the time I am passing in represents 15:30:00 GMT.
I then pass these to a php script on the server, which needs to format this timestamp as H:MM:SS (i.e., php's format('h:i:s', $time)
. I started in PHP with this code:
$dt = new DateTime();
$dt->setTimestamp($timestamp / 1000); //javascript includes milliseconds, php doesn't
echo $dt->format('h:i:s');
This produced output of 07:30:00
- which is the same point in time but using the server's timezone (server is in California).
I then used the trick from this question to get the timezone and set that timezone
$tz = timezone_name_from_abbr(null, $tzoffset * 60, true); //javascript's offset is in seconds
if($tz === false) $tz = timezone_name_from_abbr('', $tzoffset * 60, false);
$dt = new DateTime(null, new DateTimeZone($tz));
$dt->setTimestamp($timestamp / 1000);
echo $dt->format('h:i:s');
This produced a rather strange result of 02:30:00
.
I then changed the above to simply have:
$dt = new DateTime(null, new DateTimeZone('Europe/London'));
$dt->setTimestamp($timestamp / 1000);
echo $dt->format('h:i:s');
This produced the result 03:30:00
.
How do I get the server to output 15:30:00
based on the information the client supplies?
EDIT: Thanks, @MarkM, this was rather stupid of me - however this still doesn't completely solve the problem, as this code:
$tz = timezone_name_from_abbr(null, $tzoffset * 60, true); //javascript's offset is in seconds
if($tz === false) $tz = timezone_name_from_abbr('', $tzoffset * 60, false);
$dt = new DateTime(null, new DateTimeZone($tz));
$dt->setTimestamp($timestamp / 1000);
echo $dt->format('h:i:s');
now produces 14:30:00
, that is, it doesn't take into account DST. Any ideas how to solve this?
EDIT 2: I forgot that javascript's getTimezoneOffset
returns the inverse (i.e. how many minutes the GMT is from the current time). I added this one line at the top of the code in my EDIT and it's now working correctly:
$tzoffset = -$tzoffset;