Hey Stackfriends =P I know about the time() and the date() functuions, but what I want to achieve is that the user from china gets another time shown than the user from France. I cannot use JavaScript, because I am also using the local time for some calculations.
4 Answers
The only thing that should stop you from using javascript is if a) you're just serving an API and have no control over page content; or b) client has javascript blocked anyway. Via javascript is the most reliable method, short of simply prompting the user to enter their timezone.
Cookies or ajax will work. For the easier cookie way, put this javascript in your head section on any page to add a cookie...
<script>
d = new Date;
gmtoffset = d.getTimezoneOffset() / 60;
document.cookie = 'gmtoffset=' + gmtoffset;
</script>
Then in your PHP scripts, read $_COOKIE['gmtoffset']
to get their timezone relative to GMT.
IMHO, client's time w/ timezone should've been an industry-wide standard request header.
Edit: removed 'expires' date from cookie example as it may cause problems after Jan 1, 2012.

- 3,164
- 2
- 23
- 30
-
1@SuperSpy: Np. Just be sure to put a different expires date on the cookie - current client's time + a few days is always best, or leave it out so the cookie expires at end of client's browsing session. – bob-the-destroyer Jan 24 '11 at 00:28
There are two good solutions:
- Ask the user for his timezone; pre-select a default one either based on the timezone where the majority of your users come from and/or on the local timezone detected via JavaScript
- Simply use UTC (GMT) on your website.
Obviously it highly depends on your website which option is appropriate. On a site like stackoverflow option 2 is used and makes the most sense as there are various events which are day-based so days need to change at the same time for all users.

- 310,957
- 84
- 592
- 636
-
Well, I'm making a script in which the user needs to know what happened yesterday. So, your first option is the best one, in my case. Thanks, I'll accept your answer as THE answer :) – SuperSpy Jan 22 '11 at 21:24
One way would be to use something like the IP to City database from MaxMind - this can give you a timezone for the users IP adddress.
Alternatively, just ask the user what timezone they prefer and remember it in a cookie or session variable.

- 295,876
- 54
- 310
- 348
-
Not sure why reliability should be an issue for the use case you mention. You can delight the user by guessing their timezone 99% of the time, and for the remainder, let them adjust it. – Paul Dixon Jan 23 '11 at 17:10
Though I've never had to use it, there seems to be some functions enabling you to set a timezone, and other date functions to tell you the difference between the current timezone setting and the GMT. These may help you.

- 4,400
- 5
- 36
- 47