PHP Timezone Hack – Overriding server timezone

Posted by George

UPDATE Nov 2010: Much shorter code over on my Tech Blog… PHP Local Time in your timezone


As is often the case I work on servers that are not in the same timezone as I am, or servers whose time is set to Greenwich Mean Time (GMT). This PHP time hack below is something I came up with after several hours of googling and still not being able to display time on a website in whatever local timezone is desired using PHP. In this time I want a simple time output formatted like this:

09:45AM

This ‘time hack’ uses the PHP gmdate() so we are starting with GMT, and is not daylight savings time-proof.  First check out what hour your server returns with this:

<?php
$mytime = gmdate(“h:iA”); // 9:45am will be displayed as 09:45AM
echo $mytime;
?>

Ok, so now you know what time your server is showing now, so adjust for your desired timezone. For example if the server shows 09:45AM and you want it to show 08:45PM then you will be adjusting 1 hour back. If you want it to display 10:45AM then you will be adjusting 1 hour ahead. If it shows what you want, then you are done.

Now use this to get the desired time:

<?php
## get 2 pieces of the time, the hour and the minute with AM/PM
$mytime1 = gmdate(“h”); // hour
$mytime2 = gmdate(“iA”); // minute + AM/PM

## adjust the as needed
$mytime1 = $mytime1 – 4; // change subtraction to addition, if needed
//  change 4 to whatever you need
if ($mytime1 < 10) {$mytime1 = “0″ . $mytime1;} // keep a leading zero if the hour is less than 10 (if you want to)
$mytime = $mytime1 . “:” . $mytime2;

echo $mytime;
?>

RELATED POSTS

Tags:

Posted in Web Design by George | 1 Comment

1 Comment "PHP Timezone Hack – Overriding server timezone"

Leave a Comment