How to Detect User Timezone in PHP

Published on January 10, 2017

Use Cases of Getting the Browser's Timezone

Getting the user timezone can help your application in showing date and time relative to the user's browser. This means that a user in New York will see time relative to America/New_York timezone, while a user in India will see time according to the Asia/Kolkata timezone.

Another use-case can be using the user's timezone to create an event on his behalf with Calendar APIs such as that of Google and Outlook. The user can choose a time from the frontend, and in the backend the application creates an event at that time, using the browser's timezone. It should be noted that all Calendar APIs need a timezone to create an event.

Detecting the User Timezone Name

Detecting the user timezoone is a two-step process:

  1. Get the timezone offset of the browser with Javascript, and sent it to PHP (via AJAX or something).
  2. Convert the timezone offset to a valid TZ Database timezone name such as America/New_York, Asia/Kolkata.

1) Getting the Browser Timezone Offset

Javascript has a getTimezoneOffset method which gives timezone difference, in minutes, from current local time to UTC. We need to pass this offset to the server.

It should be noted that getTimezoneOffset returns an offset which is positive if the local timezone is behind UTC and negative if it is ahead. So we must add an opposite sign (+ or -) to the offset.

var timezone_offset_minutes = new Date().getTimezoneOffset();
timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;

// Timezone difference in minutes such as 330 or -360 or 0

2) In PHP, Convert Timezone Offset in Minutes to a Timezone Name

You can get the timezone name from timezone offset in minutes through the timezone_name_from_abbr function.

// This is just an example. In application this will come from Javascript (via an AJAX or something)
$timezone_offset_minutes = 330;  // $_GET['timezone_offset_minutes']

// Convert minutes to seconds
$timezone_name = timezone_name_from_abbr("", $timezone_offset_minutes*60, false);

// Asia/Kolkata
echo $timezone_name;

Now when you get the timezone name, you can get date and time relative to the user's timezone :



Click on the button below to see the name of your current timezone :

In this Tutorial