开发者

PHP users local time

Hey Stackfriends =P I know about the time() and the date() functuions, but what I wa开发者_运维问答nt 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.


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.


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.


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.


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.

http://php.net/manual/en/datetime.settimezone.php

http://php.net/manual/en/function.date.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜