Page 1 of 1

More timezone problems - a solution?

Posted: Wed Feb 28, 2007 12:56 am
by Stryks
I've been grappling with this on and off all day. The issue of formatting a given timestamp to another timezone.

This is the current solution. It seems to adjust the time and factor in daylight savings etc.

Can anyone see any problems or suggest anything better?

Code: Select all

function tz_date($format, $timestamp = false, $target_tz = false) {
	if(!$timestamp) $timestamp = time();			// No timestamp specified, use current time	
	if($target_tz) {								// If timezone is specified
		$local_tz = getenv("TZ");						// Get the original Timezone
		if(!($local_tz == $target_tz)) {				// If timezone shift required
			putenv("TZ=$target_tz");						// Set timezone accordingly 
			$result = date($format, $timestamp);			// Capture localized date/time
			putenv("TZ=" . $local_tz);						// Set timezone to original state 			
			return $result;									// Return the value
		}
	}
	return date($format, $timestamp);				// Return local time - timezone unspecified or matches
}
With this I can call :-

Code: Select all

echo tz_date('H:i:s') . "(Server) - ";
echo tz_date('H:i:s', false, "Etc/GMT") . "(GMT) - ";
echo tz_date('H:i:s', false, 'Australia/Melbourne') . "(Melbourne) - ";
echo tz_date('H:i:s') . "(Server)<br><br>";
echo tz_date('H:i:s', "1172641973") . "(Server) - ";
echo tz_date('H:i:s', "1172641973", "Etc/GMT") . "(GMT) - ";
echo tz_date('H:i:s', "1172641973" ,'Australia/Melbourne') . "(Melbourne)<br><br>";
and get :-
16:20:12(Server) - 06:50:12(GMT) - 17:50:12(Melbourne) - 16:20:12(Server)

15:22:53(Server) - 05:52:53(GMT) - 16:52:53(Melbourne)
Cheers all

Posted: Wed Feb 28, 2007 1:33 am
by feyd
Zero is a valid time stamp. Other then that, it's fine.

Posted: Wed Feb 28, 2007 6:37 am
by Stryks
This probably calls for another thread, but I've always wondered how you can take an optional parameter without messing with things.

As an example, if I pass 0 as a timestamp, it is seen as false. I have tried a few different ways, but none of which seemed to work too well.

Actually, I'd like to be able to be able to call a function with:

Code: Select all

myfunction(parameter_1, , parameter_2);
Is this possible?

Thanks

Posted: Wed Feb 28, 2007 8:10 am
by feyd
=== or type checking is my preferred methods for handling the default case.