Determine a User's Timezone

Is there any standard way for a Web Server to be able to determine a user’s timezone within a web page? Perhaps from a HTTP header? Or part of the user-agent string?

Add Comment
23 Answer(s)

javascript:

function maketimus(timestampz)
{
    var linktime = new Date(timestampz * 1000);
    var linkday = linktime.getDate();
    var freakingmonths=new Array();

    freakingmonths[0]="jan";
    freakingmonths[1]="feb";
    freakingmonths[2]="mar";
    freakingmonths[3]="apr";
    freakingmonths[4]="may";
    freakingmonths[5]="jun";
    freakingmonths[6]="jul";
    freakingmonths[7]="aug";
    freakingmonths[8]="sep";
    freakingmonths[9]="oct";
    freakingmonths[10]="nov";
    freakingmonths[11]="dec";

    var linkmonthnum = linktime.getMonth();
    var linkmonth = freakingmonths[linkmonthnum];
    var linkyear = linktime.getFullYear();
    var linkhour = linktime.getHours();
    var linkminute = linktime.getMinutes();

    if (linkminute < 10)
    {
        linkminute = "0" + linkminute;
    }

    var fomratedtime = linkday + linkmonth + linkyear + " " + linkhour + ":" + linkminute + "h";
    return fomratedtime;
}    

simply provide your times in UNIX Timestamp format to this function, javascript already knows the timezone of the user.

like this:

php:

echo '<script type="text/javascript">
var eltimio = maketimus('.$unix_timestamp_ofshiz.');
document.write(eltimio);
</script><noscript>pls enable javascript</noscript>';

this will always show the times correctly based on the timezone the person has set on his computer clock, no need to ask anything to anyone and save it into places thank god!

Answered on July 11, 2016.
Add Comment

Here is a robust JavaScript solution to determine the time zone the browser is in.

>>> var timezone = jstz.determine();
>>> timezone.name(); 
"Europe/London"

https://bitbucket.org/pellepim/jstimezonedetect

Answered on July 11, 2016.
Add Comment

Here is a more complete way.

  1. Get the timezone offset for the user
  2. Test some days on DLS boundaries to determine if they are in a zone
    that uses DLS.

Except Below:

function TimezoneDetect(){
    var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
    var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt
    var intMonth;
    var intHoursUtc;
    var intHours;
    var intDaysMultiplyBy;

    //go through each month to find the lowest offset to account for DST
    for (intMonth=0;intMonth < 12;intMonth++){
        //go to the next month
        dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);

        //To ignore daylight saving time look for the lowest offset.
        //Since, during DST, the clock moves forward, it'll be a bigger number.
        if (intOffset > (dtDate.getTimezoneOffset() * (-1))){
            intOffset = (dtDate.getTimezoneOffset() * (-1));
        }
    }

    return intOffset;
}

Getting TZ and DST from JS (via Way Back Machine)

Answered on July 11, 2016.
Add Comment

Simple with JS and PHP:

Even though the user can mess with his internal clock and/or timezone, the best way i found so far, to get the offset, remains new Date().getTimezoneOffset();. Its non-invasive, doesn’t give head-aches and eliminates the need to rely on third parties.

Say i have a table users that contains a field date_created int(13), for storing unix timestamps;

Assuming a client creates a new account, data is received by post, and i need to insert/update the date_created column with the client’s unix timestamp, not the server’s.

Since the timezoneOffset is needed at the time of insert/update, it is passed as an extra $_POST element when the client submits the form, thus eliminating the need to store it in sessions and/or cookies, and no additional server hits either.

var off = (-new Date().getTimezoneOffset()/60).toString();//note the '-' in front which makes it return positive for negative offsets and negative for positive offsets
var tzo = off == '0' ? 'GMT' : off.indexOf('-') > -1 ? 'GMT'+off : 'GMT+'+off;

Say the server receives tzo as $_POST['tzo'];

$ts = new DateTime('now', new DateTimeZone($_POST['tzo']);
$user_time = $ts->format("F j, Y, g:i a");//will return the users current time in readable format, regardless of whether date_default_timezone() is set or not.
$user_timestamp = strtotime($user_time);

Insert/update date_created=$user_timestamp.

When retrieving the date_created, you can convert the timestamp like so:

$date_created = //get from db
$created = date("F j, Y, g:i a",$date_created);//return it to the user or whatever

Now, this example may fit one’s needs, when it comes to inserting a first timestamp… When it comes to an additional timestamp, or table, u may want to consider inserting the tzo value into the users table for future reference, or setting it as session or as a cookie.

P.S. BUT what if the user travels and switches timezones. Logs in at GMT+4, travels fast to GMT-1 and logs in again. Last login would be in the future.

I think… we think too much.

Answered on July 11, 2016.
Add Comment

With PHP date function you will get the date time of server on which site is located. The only way to get user time is to use JavaScript.

But I suggest you to, if your site have registration required then best way is to ask user while registration as compulsory field. You can list various time zones in register page and save that in database. After this if user login to site then you can set default time zone for that session as per users’ selected time zone. You can set any specific time zone using PHP function date_default_timezone_set. This set the specified time zone for users.

Basically users’ time zone is goes to client side, so we must use JavaScript for this.

Below is the script to get users’ time zone using PHP and JavaScript.

<?php
#http://www.php.net/manual/en/timezones.php List of Time Zones
function showclienttime()
{
  if(!isset($_COOKIE['GMT_bias']))
  {
    ?>
    <script type="text/javascript">
    var Cookies = {};
    Cookies.create = function (name, value, days) {
      if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
      } else {
        var expires = "";
      }
      document.cookie = name + "=" + value + expires + "; path=/";
      this[name] = value;
    }

    var now = new Date();
    Cookies.create("GMT_bias",now.getTimezoneOffset(),1);
    window.location = "<?php echo $_SERVER['PHP_SELF'];?>";
    </script>
    <?php
  } else {
    $fct_clientbias = $_COOKIE['GMT_bias'];
  }

  $fct_servertimedata = gettimeofday();
  $fct_servertime = $fct_servertimedata['sec'];
  $fct_serverbias = $fct_servertimedata['minuteswest'];
  $fct_totalbias = $fct_serverbias – $fct_clientbias;
  $fct_totalbias = $fct_totalbias * 60;
  $fct_clienttimestamp = $fct_servertime + $fct_totalbias;
  $fct_time = time();
  $fct_year = strftime("%Y", $fct_clienttimestamp);
  $fct_month = strftime("%B", $fct_clienttimestamp);
  $fct_day = strftime("%d", $fct_clienttimestamp);
  $fct_hour = strftime("%I", $fct_clienttimestamp);
  $fct_minute = strftime("%M", $fct_clienttimestamp);
  $fct_second = strftime("%S", $fct_clienttimestamp);
  $fct_am_pm = strftime("%p", $fct_clienttimestamp);
  echo $fct_day.", ".$fct_month." ".$fct_year." ( ".$fct_hour.":".$fct_minute.":".$fct_second." ".$fct_am_pm." )";
}

showclienttime();
?>

But as per my point of view, it’s better to ask to the users if registration is mandatory in your project.

Answered on July 11, 2016.
Add Comment

Here’s how I do it. This will set the PHP default timezone to the user’s local timezone. Just paste the following on the top of all your pages:

<?php
session_start();

if(!isset($_SESSION['timezone']))
{
    if(!isset($_REQUEST['offset']))
    {
    ?>
        <script>
        var d = new Date()
        var offset= -d.getTimezoneOffset()/60;
        location.href = "<?php echo $_SERVER['PHP_SELF']; ?>?offset="+offset;
        </script>
        <?php   
    }
    else
    {
        $zonelist = array('Kwajalein' => -12.00, 'Pacific/Midway' => -11.00, 'Pacific/Honolulu' => -10.00, 'America/Anchorage' => -9.00, 'America/Los_Angeles' => -8.00, 'America/Denver' => -7.00, 'America/Tegucigalpa' => -6.00, 'America/New_York' => -5.00, 'America/Caracas' => -4.30, 'America/Halifax' => -4.00, 'America/St_Johns' => -3.30, 'America/Argentina/Buenos_Aires' => -3.00, 'America/Sao_Paulo' => -3.00, 'Atlantic/South_Georgia' => -2.00, 'Atlantic/Azores' => -1.00, 'Europe/Dublin' => 0, 'Europe/Belgrade' => 1.00, 'Europe/Minsk' => 2.00, 'Asia/Kuwait' => 3.00, 'Asia/Tehran' => 3.30, 'Asia/Muscat' => 4.00, 'Asia/Yekaterinburg' => 5.00, 'Asia/Kolkata' => 5.30, 'Asia/Katmandu' => 5.45, 'Asia/Dhaka' => 6.00, 'Asia/Rangoon' => 6.30, 'Asia/Krasnoyarsk' => 7.00, 'Asia/Brunei' => 8.00, 'Asia/Seoul' => 9.00, 'Australia/Darwin' => 9.30, 'Australia/Canberra' => 10.00, 'Asia/Magadan' => 11.00, 'Pacific/Fiji' => 12.00, 'Pacific/Tongatapu' => 13.00);
        $index = array_keys($zonelist, $_REQUEST['offset']);
        $_SESSION['timezone'] = $index[0];
    }
}

date_default_timezone_set($_SESSION['timezone']);

//rest of your code goes here
?>
Answered on July 11, 2016.
Add Comment

The magic all seems to be in

visitortime.getTimezoneOffset()

That’s cool, I didn’t know about that. Does it work in IE, etc?
From there you should be able to use JS to ajax, set cookies, whatever. I’d probably go the cookie route myself.

You’ll need to allow the user to change it though. We tried to use geolocation (via maxmind) to do this a while ago, and it was wrong reasonably often – enough to make it not worth doing, so we just let the user set it in their profile, and show a notice to users who haven’t set theirs yet.

Answered on July 11, 2016.
Add Comment

There are no HTTP headers that will report the clients timezone so far although it has been suggested to include it in the HTTP specification.

If it was me, I would probably try to fetch the timezone using clientside JavaScript and then submit it to the server using Ajax or something.

Answered on July 11, 2016.
Add Comment

Anyone know of any services that will
match IP to geographic location

Well, lucky for you that answer can be found on our very own stackoverflow website:
http://stackoverflow.com/questions/1033/ip-to-country

spoiler: http://www.hostip.info/use.html

Answered on July 11, 2016.
Add Comment

Here is an article (with source code) that explains how to determine and use localized time in an ASP.NET (VB.NET, C#) application:

It’s About Time

In short, the described approach relies on the JavaScript getTimezoneOffset function, which returns the value that is saved in the session cookie and used by code-behind to adjust time values between GMT and local time. The nice thing is that the user does not need to specify the time zone (the code does it automatically). There is more involved (this is why I link to the article), but provided code makes it really easy to use. I suspect that you can convert the logic to PHP and other languages (as long as you understand ASP.NET).

Answered on July 11, 2016.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.