-->

PHP users local time

2019-05-31 11:27发布

问题:

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.

回答1:

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.



回答2:

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:

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.



回答4:

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



标签: php localtime