How to automatically detect user's timezone?

2019-01-07 19:58发布

hi i am creating a web application , where if a user register we will show the created date.

For that we are using Current time stamp in my sql table.Which shows server Time.But we don't know how to convert Time according to user time zone.

Because we are not getting user's country .

Can any on help me to fix it

Thanks in advance :)

标签: php timezone
5条回答
闹够了就滚
2楼-- · 2019-01-07 20:22

With a small "cheating" (using client side scripting) and posting the result to your server, you can access your client's timezone.

For example you can use this javascript library:

https://bitbucket.org/pellepim/jstimezonedetect

var tz = jstz.determine(); // Determines the time zone of the browser client
tz.name(); // Returns the name of the time zone eg "Europe/Berlin"

Demo: http://pellepim.bitbucket.org/jstz/

查看更多
Deceive 欺骗
3楼-- · 2019-01-07 20:25

For geolocation you can use http://ipinfodb.com/, work great with an API!

function GeoLocation($precision='city',$ip,$api) {

    if($precision == "country") {
        $file = "ip_query_country.php";
    }
    else {
        $file = "ip_query.php";
    }

    $params = @file_get_contents("http://api.ipinfodb.com/v2/ip_query.php?key=".$api."&ip=".$ip."&timezone=true");
    $fields = @new SimpleXMLElement($params);
    foreach($fields as $field => $val) {
        $result[(string)$field] = (string)$val;
    }
    return $result;
}
查看更多
Melony?
4楼-- · 2019-01-07 20:34
我命由我不由天
5楼-- · 2019-01-07 20:38

The most reliable method is to ask the user to set his own timezone. I think it's a good idea to have a timestamp of when the users account was created in your own database for your own use.

These are the steps I would take to have a users timezone:

1- Preserve the timestamp column that you have for your own usage
2- Add a new column for the actual users timezone
3- Use javascript to retrieve the timezone:
new Date().getTimezoneOffset()/60;<br/>
4- Also allow users to set there own timezone as well

You can also take it a step further and use a geo-location service to detect a users timezone.

查看更多
乱世女痞
6楼-- · 2019-01-07 20:49

You can't get a user's timezone on the server side, and you can only make a guess at it on the client side.

If you rely on getting the user's IP address then you could geolocate that and deduce a time.

The way this is usually done is by asking the user (when they register, for instance) what timezone they are in and then use this in your time calculations.

查看更多
登录 后发表回答