I’ve been storing user messages in my database using DATETIME columns. I need to display the message’s sent time to users in different countries, since the database uses GMT+0 I need to adjust the retrieved time to the user’s timezone.
The current user’s timezone has been set with date_default_timezone_set() How do I get the it’s GMT +- time?
EDIT
Following the idea of @doniyor this is what I did:
// Get server hour
$localtime = localtime();
$serverHour = $localtime[2]; # The server's timezone is used by default before defining one
// Set timezone
date_default_timezone_set('user's timezone goes here');
// Get user hour
$localtime = localtime(); # Now localtime gives the user's time since timezone has been changed
$userHour = $localtime[2];
$timeAdjustment = $userHour - $serverHour < -12 ? 24 + $userHour - $serverHour : $userHour - $serverHour; // Calculate hours to add to rows got from db to match user's time
// Example of a row adjusted to match user's time
$adjustTime = ($userHour - $serverHour < -12 ? 24 + $userHour - $serverHour : ($userHour - $serverHour > 12 ? $userHour - $serverHour - 24 : $userHour - $serverHour)*60*60; // strtotime is in seconds so $timeAdjustment needs *60*60 to convert to seconds too
I’ve tested this on PHP5+Apache but probably results vary depending on server configuration.
If wrong, please dont downvote 🙂
If you get the timezone time in client browser and check the difference, if there is difference, then add or substract this difference-value depending on the location of the client.