Many websites need to display the time of some event, which is local for the logging user. For this, there needs to first get the time zone of that user. In this article, we will see the way to determine the time zone of the current user.
In my previous article Get IP Address and Geo Location of Login User, I have described the simplest way to get the user’s GEO Location using his IP address. Now just take it further to get the user’s time zone.
Getting Time Zone of User Through IP Address
Before using the below code, you need to get an API KEY for Google Maps Time Zone API, that you can get from Google developer console.
To get time zone using IP address, need to include “GoogleMapsTimeZone.php” file. This is the class file defining all the functionality implementation. You can find this class file code on Github.
Check below code “example.php” file, in which we are getting the timezone of the user through IP address.
Example.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<?php // include the google map time zone library to get results require_once ('GoogleMapsTimeZone.php'); /** * All queries require an API key from Google * @link https://developers.google.com/maps/documentation/timezone/get-api-key * */ define('API_KEY', 'YOUR API KEY HERE'); if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } //code to get user location details using his IP address $user_ip = $ip; $url = "http://ipinfo.io/".$user_ip; $ip_info = json_decode(file_get_contents($url)); $loc = $ip_info->loc; $loc_array = explode(',',$loc); $lat = $loc_array[0]; $long = $loc_array[1]; // Initialize GoogleMapsTimeZone object $timezone_object = new GoogleMapsTimeZone($lat, $long, GoogleMapsTimeZone::FORMAT_JSON); // Set Google API key $timezone_object->setApiKey(API_KEY); // Perform query $timezone_data = $timezone_object->queryTimeZone(); echo '<pre>'; print_r($timezone_data); echo '</pre>'; ?> |
Get that straight code on your website and show the user time zone on the basis of IP address.
If you like this tutorial, please share it with others. Thanks