This question already has an answer here:
I need to know what time zone is currently my users are in based on their IP or http header.
I got many answer regarding this issue, but i could not understood those answer. Some said use -new Date().getTimezoneOffset()/60
(from here). But what does it mean?
I have a date_default_timezone_set("Asia/Calcutta");
in the root of my (index.php) page. So for this I have to get the timezone dynamically and set it in place of Asia/Calcutta
.
To summarize Matt Johnson's answer in terms of code:
This works fine...
Dependencies:
http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
citation: SGet visitor local time, sunrise and sunset time by IP with MaxMind GeoIP and PHP by Stanislav Khromov
Timezone is not available in the HTTP header, but country (abbreviation) is in the ACCEPT_LANGUAGE header. It'll be something like "en-US" (US is the country code). This can be combined with the JavaScript information to get a good idea of the user's timezone.
This is what I'm using in JS:
This returns a string like "-6S1" for the central zone (standard time offset of -6 hours, DST active in the summer and adds 1 hour). I use a cookie to make this available to PHP. PHP searches the TZ database for zones that match this, and the country. For here (US, -6S1) there are 7 matching zones, the first is "America/Chicago".
BTW, there are 2 zones in the database where DST adds something other than 1 hour: Lord Howe Island (10.5W0.5) and Troll Station, Antarctica (0W2).
Time zone information of the browser is not part of the HTTP spec, so you can't just get it from a header.
If you have location coordinates (from a mobile device GPS, for example), then you can find the time zone using one of these methods. However, geolocation by IP address is not a great solution because often the IP is that of an ISP or proxy server which may be in another time zone.
There are some strategies you can use to try to detect the time zone, such as using jsTimeZoneDetect library, which is a great starting point, but imperfect enough that you can't just rely on that alone. If you're using moment.js, there's a built in function in moment-timezone called
moment.tz.guess()
that does the same thing.The idea of using JavaScript's
getTimezoneOffset()
function is flawed in that you are not getting a time zone - just a single offset for a particular date. See the TimeZone tag wiki's section titled "TimeZone != Offset".However you look at it, ultimately you have to decide on one of two approaches:
OR
I discuss this in more detail (from a c# perspective) in this answer.
One solution is to ask them! Especially on members systems where you can capture/register a user - give them a choice at that point. Simple but accurate.