Page 1 of 1

Modify timestamp by GMT?

Posted: Sat Jul 08, 2006 4:18 am
by Starcraftmazter
Hey.

How would I take a timestamp, and then modify it by a GMT value to display the correct time for all visitors of a website?

Thanks.

Posted: Sat Jul 08, 2006 5:11 am
by Oren
Assuming $users_local_time_in_seconds holds the user's time zone in seconds. Example:
For a user whose time zone is GMT +4 hours $users_local_time_in_seconds should hold 14400 (3600 * 4).

Code: Select all

/* The date() function adjust the date to the server's local time and therefore we first subtract the difference between the server to the GMT - this way, what happens is as follow:

time() returns the time since January 1 1970 00:00:00 GMT in seconds, then we subtract from this the difference between the server and the GMT. When we call to date(), date() adds the difference between the two - which is exactly what we just subtracted, and as a result date() is "forced" to return the time according to the GMT and not the server's time zone */

$time = time() - date('Z');
$time += $users_local_time_in_seconds;

echo date('r', $time);
Just in case you don't understand my explanation here is a simple example:

Let's say that right now the time is January 1 1970 01:00:00 GMT. When we call time() it will return 3600 (1 hour in seconds).
Also let's say that the server's time zone is GMT +4 hours.
Now if we call date() and supply it with the result from time(), instead of printing something like: January 1 1970 01:00:00 GMT, it will print: January 1 1970 04:00:00 GMT since date() automatically adjusts its result to match to the server's local time zone. But we wanted the GMT time - so we subtract the result of date('Z') from the result of time() before we call to date().
date('Z') means (from the PHP Manual):
Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.

P.S You should take care of daylight saving time too - which I didn't in my example, this is up to you.

I hope this helps. If you don't understand something feel free to ask 8)

Posted: Sat Jul 08, 2006 8:24 am
by feyd
Why not just use gmmktime() instead?

Posted: Sat Jul 08, 2006 9:24 am
by Oren
How would that help? The date() function would adjust the time to match the server's time zone.

Posted: Sat Jul 08, 2006 9:46 am
by feyd
Oren wrote:How would that help? The date() function would adjust the time to match the server's time zone.
hmm, you're right. I must have been thinking of something else.. well there's always

Code: Select all

$t = strtotime(gmdate('Y-m-d H:i:s'));
:)

Posted: Sat Jul 08, 2006 10:26 am
by Oren
I don't think that

Code: Select all

$t = strtotime(gmdate('Y-m-d H:i:s'));
could help here, but the gmdate() function certainly can:

Code: Select all

echo gmdate('r', time() + $users_local_time_in_seconds)