If you want to achieve this just using PHP:
- Fetch User's IP Address
- Locate User's Location based on their IP Address. This can be done using 3rd Party API or, GEO IP Databases
- Get User's Timezone with the Country Code and with/without Region Code
- Get Time According to the timezone.
MaxMind's Dev: https://dev.maxmind.com/geoip/
Code:
<?php
if(!isset($_COOKIE['timezone'])){
$ip = $_SERVER['REMOTE_ADDR'];
//Open GeoIP database and query our IP
$gi = geoip_open("GeoLiteCity.dat", GEOIP_STANDARD);
$record = geoip_record_by_addr($gi, $ip);
//If we for some reason didnt find data about the IP, default to a preset location.
//You can also print an error here.
if(!isset($record))
{
$record = new geoiprecord();
$record->latitude = 59.2;
$record->longitude = 17.8167;
$record->country_code = 'SE';
$record->region = 26;
}
//Calculate the timezone and local time
try
{
//Create timezone
$user_timezone = new DateTimeZone(get_time_zone($record->country_code, ($record->region!='') ? $record->region : 0));
setcookie("timezone", $user_timezone, time() + (86400 * 30), "/"); //setting cookie to the browser for reference
//Create local time
$user_localtime = new DateTime("now", $user_timezone);
$user_timezone_offset = $user_localtime->getOffset();
}
//Timezone and/or local time detection failed
catch(Exception $e)
{
$user_timezone_offset = 7200;
$user_localtime = new DateTime("now");
}
echo 'User local time: ' . $user_localtime->format('H:i:s') . '<br/>';
echo 'Timezone GMT offset: ' . $user_timezone_offset . '<br/>';
}
?>
<script type="text/javascript">
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
if(getCookie('timezone')!=Intl.DateTimeFormat().resolvedOptions().timeZone){
document.cookie = "timezone="+Intl.DateTimeFormat().resolvedOptions().timeZone;
location.reload();
}
</script>
Note: PHP code might not be effective all the time. The javascript code written above will ensure that the PHP-fetched timezone match the timezone with the browser, otherwise it updates the timezone info in cookie and reloads the page.