I searched the forums but didn't find an answer... I allow users to select their timezone offset - say -5 for Eastern Standard Time. However, it could be Eastern Daylight Time, like it is right now, in which case it is actually -4. How do I detect if their time is in DST and adjust accordingly? The server time is GMT...
date_default_timezone_set() and the list of supported timezones. Make a dropdown with all timezones, and save the selected one in a session or elsewhere, and call the above function with the given timezone at the top of your scripts.
I know what you mean - how do you automatically detect for daylight saving time? I haven't had to use it, but the date() function takes a parameter, I, which determines whether or not the current date is in DST or not: http://www.php.net/date I'd imagine you could use that by having the user specify their timezone first, and then when you display the current time check with the date(I) function to see if that timezone is in DST or not, and adjust the displayed time accordingly.
The "I" indicates if the date is in DST based on SERVER time.... It seems as though this is actually quite complicates because there could be certain places in a timezone that don't observe DST... I wonder how vBulletin does it with their "automatically detect DST"...
vBulletin uses a little Javascript/PHP trick: <!-- auto DST correction code --> <form action="/profile.php?do=dst" method="post" name="dstform"> <input type="hidden" name="s" value="$session[sessionhash]" /> <input type="hidden" name="do" value="dst" /> </form> <script type="text/javascript"> <!-- var tzOffset = $bbuserinfo[timezoneoffset] + $bbuserinfo[dstonoff]; var utcOffset = new Date().getTimezoneOffset() / 60; if (Math.abs(tzOffset + utcOffset) == 1) { // Dst offset is 1 so its changed document.forms.dstform.submit(); } //--> </script> <!-- / auto DST correction code --> Code (javascript):
The "I" checks for DST based on any date passed to it - not just server time. You can use the function on that PHP page to check for DST on any date passed to it: <?php function zonedate($layout, $countryzone, $daylightsaving, $time) { if($daylightsaving) { $daylight_saving = date('I'); if($daylight_saving){ $zone=3600*($countryzone+1); } } else { if( $countryzone>>0){ $zone=3600*$countryzone; } else { $zone=0; } } if(!$time) { $time = time(); } $date = gmdate($layout, $time + $zone); return $date; } ?> Code (markup): For example if I wanted the time and date of my birthday in New Zealand time; <?php echo zonedate('Y-m-d H:i:s',-12,true,mktime(18,46,0,9,7,1986)); ?> Code (markup):