Is there a standard way for a web server to be able to determine a user's timezone within a web page?
Perhaps from an HTTP header or part of the user-agent
string?
original title: "html - Determine a user's timezone"
Is there a standard way for a web server to be able to determine a user's timezone within a web page?
Perhaps from an HTTP header or part of the user-agent
string?
क्या वेब सर्वर के लिए एक मानक तरीका है जो किसी वेब पेज के भीतर उपयोगकर्ता के टाइमज़ोन को निर्धारित करने में सक्षम हो सकता है? शायद एक HTTP शीर्ष लेख या उपयोगकर्ता-एजेंट स्ट्रिंग के भाग से?
यह अनुवाद के बाद का सारांश है, अगर आपको पूरा अनुवाद देखने की आवश्यकता है, तो कृपया 'अनुवाद' आइकन पर क्लिक करें
The method
getTimezoneOffset()
will subtract your time from GMT and return the number of minutes. So if you live in GMT-8, it will return 480.To put this into hours, divide by 60. Also, notice that the sign is the opposite of what you need - it's calculating GMT's offset from your time zone, not your time zone's offset from GMT. To fix this, simply multiply by -1.
Also note that w3school says:
The most popular (==standard?) way of determining the time zone I've seen around is simply asking the users themselves. If your website requires subscription, this could be saved in the users' profile data. For anon users, the dates could be displayed as UTC or GMT or some such.
I'm not trying to be a smart aleck. It's just that sometimes some problems have finer solutions outside of any programming context.
There are no HTTP headers that will report the clients timezone so far although it has been suggested to include it in the HTTP specification.
If it was me, I would probably try to fetch the timezone using clientside JavaScript and then submit it to the server using Ajax or something.
JavaScript is the easiest way to get the client's local time. I would suggest using an XMLHttpRequest to send back the local time, and if that fails, fall back to the timezone detected based on their IP address.
As far as geolocation, I've used MaxMind GeoIP on several projects and it works well, though I'm not sure if they provide timezone data. It's a service you pay for and they provide monthly updates to your database. They provide wrappers in several web languages.
Here is a robust JavaScript solution to determine the time zone the browser is in.
https://bitbucket.org/pellepim/jstimezonedetect
Here is a more complete way.
An excerpt is below:
Getting TZ and DST from JS (via Way Back Machine)
First, understand that time zone detection in JavaScript is imperfect. You can get the local time zone offset for a particular date and time using
getTimezoneOffset
on an instance of theDate
object, but that's not quite the same as a full IANA time zone likeAmerica/Los_Angeles
.There are some options that can work though:
Most modern browsers support IANA time zones in their implementation of the ECMAScript Internationalization API, so you can do this:
The result is a string containing the IANA time zone setting of the computer where the code is running.
Supported environments are listed in the Intl compatibility table. Expand the
DateTimeFormat
section, and look at the feature namedresolvedOptions().timeZone defaults to the host environment
.luxon.Settings.defaultZoneName
.If you need to support an wider set of environments, such as older web browsers, you can use a library to make an educated guess at the time zone. They work by first trying the
Intl
API if it's available, and when it's not available, they interrogate thegetTimezoneOffset
function of theDate
object, for several different points in time, using the results to choose an appropriate time zone from an internal data set.Both jsTimezoneDetect and moment-timezone have this functionality.
In both cases, the result can only be thought of as a guess. The guess may be correct in many cases, but not all of them.
Additionally, these libraries have to be periodically updated to counteract the fact that many older JavaScript implementations are only aware of the current daylight saving time rule for their local time zone. More details on that here.
Ultimately, a better approach is to actually ask your user for their time zone. Provide a setting that they can change. You can use one of the above options to choose a default setting, but don't make it impossible to deviate from that in your app.
There's also the entirely different approach of not relying on the time zone setting of the user's computer at all. Instead, if you can gather latitude and longitude coordinates, you can resolve those to a time zone using one of these methods. This works well on mobile devices.
Using Unkwntech's approach, I wrote a function using jQuery and PHP. This is tested and does work!
On the PHP page where you want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:
This will read the session variable "time", which we are now about to create.
On the same page, in the <head>, you need to first of all include jQuery:
Also in the <head>, below the jQuery, paste this:
You may or may not have noticed, but you need to change the URL to your actual domain.
One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above URL)
If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.
To submit the timezone offset as an HTTP header on AJAX requests with jQuery
You can also do something similar to get the actual time zone name by using
moment.tz.guess();
from http://momentjs.com/timezone/docs/#/using-timezones/guessing-user-timezone/I still have not seen a detailed answer here that gets the time zone. You shouldn't need to geocode by IP address or use PHP (lol) or incorrectly guess from an offset.
Firstly a time zone is not just an offset from GMT. It is an area of land in which the time rules are set by local standards. Some countries have daylight savings, and will switch on DST at differing times. It's usually important to get the actual zone, not just the current offset.
If you intend to store this timezone, for instance in user preferences you want the zone and not just the offset. For realtime conversions it won't matter much.
Now, to get the time zone with javascript you can use this:
However I found it easier to simply use this robust plugin which returns the Olsen formatted timezone:
https://github.com/scottwater/jquery.detect_timezone
With the PHP
date
function you will get the date time of server on which the site is located. The only way to get the user time is to use JavaScript.But I suggest you to, if your site has registration required then the best way is to ask the user while to have registration as a compulsory field. You can list various time zones in the register page and save that in the database. After this, if the user logs in to the site then you can set the default time zone for that session as per the users’ selected time zone.
You can set any specific time zone using the PHP function
date_default_timezone_set
. This sets the specified time zone for users.Basically the users’ time zone is goes to the client side, so we must use JavaScript for this.
Below is the script to get users’ time zone using PHP and JavaScript.
But as per my point of view, it’s better to ask to the users if registration is mandatory in your project.
JavaScript:
Simply provide your times in Unix timestamp format to this function; JavaScript already knows the timezone of the user.
Like this:
PHP:
This will always show the times correctly based on the timezone the person has set on his/her computer clock. There is no need to ask anything to anyone and save it into places, thank god!
Don't use the IP address to definitively determine location (and hence timezone)-- that's because with NAT, proxies (increasingly popular), and VPNs, IP addresses do not necessarily realistically reflect the user's actual location, but the location at which the servers implementing those protocols reside.
Similar to how US area codes are no longer useful for locating a telephone user, given the popularity of number portability.
IP address and other techniques shown above are useful for suggesting a default that the user can adjust/correct.
Easy, just use the JavaScript
getTimezoneOffset
function like so:The magic all seems to be in
That's cool, I didn't know about that. Does it work in Internet Explorer, etc? From there you should be able to use JavaScript to Ajax, set cookies, whatever. I'd probably go the cookie route myself.
You'll need to allow the user to change it though. We tried to use geolocation (via maxmind) to do this a while ago, and it was wrong reasonably often - enough to make it not worth doing, so we just let the user set it in their profile, and show a notice to users who haven't set theirs yet.
If you happen to be using OpenID for authentication, Simple Registration Extension would solve the problem for authenticated users (You'll need to convert from tz to numeric).
Another option would be to infer the time zone from the user agent's country preference. This is a somewhat crude method (won't work for en-US), but makes a good approximation.
Here is an article (with source code) that explains how to determine and use localized time in an ASP.NET (VB.NET, C#) application:
It's About Time
In short, the described approach relies on the JavaScript
getTimezoneOffset
function, which returns the value that is saved in the session cookie and used by code-behind to adjust time values between GMT and local time. The nice thing is that the user does not need to specify the time zone (the code does it automatically). There is more involved (this is why I link to the article), but provided code makes it really easy to use. I suspect that you can convert the logic to PHP and other languages (as long as you understand ASP.NET).It is simple with JavaScript and PHP:
Even though the user can mess with his/her internal clock and/or timezone, the best way I found so far, to get the offset, remains
new Date().getTimezoneOffset();
. It's non-invasive, doesn't give head-aches and eliminates the need to rely on third parties.Say I have a table,
users
, that contains a fielddate_created int(13)
, for storing Unix timestamps;Assuming a client
creates a new account
, data is received bypost
, and I need toinsert/update
thedate_created column
with the client's Unix timestamp, not the server's.Since the timezoneOffset is needed at the time of insert/update, it is passed as an extra $_POST element when the client submits the form, thus eliminating the need to store it in sessions and/or cookies, and no additional server hits either.
Say the server receives
tzo
as$_POST['tzo']
;Insert/update
date_created=$user_timestamp
.When retrieving the date_created, you can convert the timestamp like so:
Now, this example may fit one's needs, when it comes to inserting a
first
timestamp... When it comes to an additional timestamp, or table, you may want to consider inserting the tzo value into the users table for future reference, or setting it as session or as a cookie.P.S. BUT what if the user travels and switches timezones. Logs in at GMT+4, travels fast to GMT-1 and logs in again. Last login would be in the future.
I think... we think too much.
You could do it on the client with moment-timezone and send the value to server; sample usage:
Getting a valid TZ Database timezone name in PHP is a two-step process:
With JavaScript, get timezone offset in minutes through
getTimezoneOffset
. This offset will be positive if the local timezone is behind UTC and negative if it is ahead. So you must add an opposite sign to the offset.Pass this offset to PHP.
In PHP convert this offset into a valid timezone name with timezone_name_from_abbr function.
I've written a blog post on it: How to Detect User Timezone in PHP. It also contains a demo.
A simple way to do it is by using:
One possible option is to use the
Date
header field, which is defined in RFC 7231 and is supposed to include the timezone. Of course, it is not guaranteed that the value is really the client's timezone, but it can be a convenient starting point.Here's how I do it. This will set the PHP default timezone to the user's local timezone. Just paste the following on the top of all your pages:
Try this PHP code: