More timezone problems - a solution?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

More timezone problems - a solution?

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Zero is a valid time stamp. Other then that, it's fine.
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

=== or type checking is my preferred methods for handling the default case.
Post Reply