Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

PHP - Convert server timestamp to localtime?

Status
Not open for further replies.

cmayo

MIS
Apr 23, 2001
159
US
Sorry if this is been asked before, but I need to convert a server timestamp in the form of "YYYY-MM-DD HH:MM:SS" to a different timezone.

I have the local GMT offset in a configuration variable, is there an easy way to maybe convert the server timestamp to GMT, then apply the local offset to the GMT timestamp and arrive at a localized version of the timestamp? How would I code that?

Or am I making this too hard?

Thanks,
Chuck
 
let's assume that your server is based in New York (EST) and you want to convert to your local timezone, based in Toulouse, France (CET).

Code:
//set local timezone
date_default_timezone_set("Europe/Paris");

//get server time as a unix timestamp
$unixtime = strtotime($servertime . ' EST'); //append EST to denote New York time

//convert to human readable local time
echo 'server time is '.date('r', $unixtime);
 
Thanks very much for the suggestion, but my server's running PHP 4.4.4 and doesn't support date_default_timezone_set.

Also, I really need something that'll convert a MySQL-type timestamp like "2008-01-24 09:57:17" (server time) to the same sort of timestamp adjusted to the users' local time, i.e. "2008-01-24 07:57:17."

I did find some code online which seems to nicely convert the current server time to local time...

Code:
// Convert current servertime to GMT so the local time can be calculated 
function fetchGMT() 
{ 
    return mktime () + ((date('O')/100 )/-1)*60*60 ; 
}
 
// What is the hour offset for OUR timezone? 
// We are in GMT -6, so -6 is our offset! 
$localoffset=-6 ; 

$gmt=fetchGMT();  // Get GMT time 
$timezoneoffset=$localoffset* 60*60; // Get offset between local and GMT 
$local_time=$gmt+$timezoneoffset ; // Add offset to get local time

...but I'm getting myself all tripped up trying to modify that function to accept and return the timestamp. I dunno why these time functions confuse me so much...

Any ideas?
 
Code:
//set local timezone
putenv("TZ=Europe/Paris");

//get server time as a unix timestamp
$unixtime = strtotime($servertime . ' EST'); //append EST to denote New York time

//convert to human readable local time
echo 'server time is '.date('r', $unixtime);

your code is just a maths solution - try to use the built in functions of php to handle the time zone (and daylight savings time etc) conversions for you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top