PHP - Show visitor local time

In this tutorial we demonstrate how to determine a website visitor's timezone and show their local time based on their IP address with PHP using an API call or a local database query.


API call

The easiest way to show a website visitor's local time is through an API call, the only prerequisite is the API client class, see the PHP code example below :

<?php
// The free open source DB-IP API client is available on GitHub : https://github.com/dbip/api-client
require "dbip-client.class.php";

// Uncomment the line below and fill in your API key
//DBIP\APIKey::set("YOUR_API_KEY_GOES_HERE");

// Get IP address from the $_SERVER global array, catch forwarded address from proxies
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]) && $_SERVER["HTTP_X_FORWARDED_FOR"]) {
	$ipAddress = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else {
	$ipAddress = $_SERVER["REMOTE_ADDR"];
}

// Lookup IP address information
$addrInfo = DBIP\Address::lookup($ipAddress);

// Create DateTime object with the right time zone
$now = new DateTime("now", new DateTimeZone($addrInfo->timeZone));

// Display results
echo "Visitor local time : " . $now->format("H:i:s");


Local database query

In the code example below, we assume you are using the latest database query library and already imported a CSV database to a local MySQL or MariaDB instance :

<?php
// The free open source DB-IP query library is available at : https://db-ip.com/db/#source_code
require "dbip.class.php";

// Connect to the database
$db = new PDO("mysql:host=localhost;dbname=dbip", "mylogin", "mypassword");

// Alternatively connect to MySQL using the old interface
// Comment the PDO statement above and uncomment the mysql_ calls
// below if your PHP installation doesn't support PDO :
// $db = mysql_connect("localhost", "mylogin", "mypassword");
// mysql_select_db("dbip", $db);

// Instanciate a new DBIP object with the database connection
$dbip = new DBIP($db);

// Alternatively instanciate a DBIP_MySQL object
// Comment the new statement above and uncomment below if your PHP
// installation doesn't support PDO :
// $dbip = new DBIP_MySQL($db);

// Get IP address from the $_SERVER global array, catch forwarded address from proxies
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]) && $_SERVER["HTTP_X_FORWARDED_FOR"]) {
	$ipAddress = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else {
	$ipAddress = $_SERVER["REMOTE_ADDR"];
}

// Lookup IP address information in local database
$addrInfo = $dbip->lookup($ipAddress);

// Create DateTime object with the right time zone
$now = new DateTime("now", new DateTimeZone($addrInfo->timezone_name));

// Display results
echo "Visitor local time : " . $now->format("H:i:s");

Compatibility

API DB
Free Basic Core Extended IP to Country IP to City IP to Location IP to ISP IP to Location+ISP

Was this article helpful ? Share it with others by clicking the social media buttons !