lisovaccaro
lisovaccaro

Reputation: 33966

Get a timezone GMT time?

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.

Upvotes: 1

Views: 165

Answers (3)

doniyor
doniyor

Reputation: 37904

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.

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173642

Just pass the values of the date values to JavaScript as a UNIX timestamp. For example, using AJAX:

echo json_encode(array(
    'time' => strtotime($row['msg_time']),
    'msg' => 'hello world',
));

Then, use Date() to convert it into the user's local time:

var msgTime = new Date(data.time * 1000);

Upvotes: 1

user149341
user149341

Reputation:

The current user's timezone has been set with date_default_timezone_set() How do I get the it's GMT +- time?

You can't. Due to the vagaries of Daylight Saving Time, the offset is not constant -- it can change depending on the date.

Use gmmktime() (together with a bit of string parsing) to convert a GMT date/time to a UNIX timestamp, then use date() to display that in the current time zone.

Upvotes: 2

Related Questions