get users’ timezone using php and javascript

You might have not faced this problem if you have not work in any project which is very strict in timing. But projects like scheduling and other tasks like users’ subscription with payment must have this features enabled.

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.

List of supported time zones can be found here.

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.

  # List of Time Zones
  function showclienttime()
 <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();
 //window.location = "<?php echo $_SERVER['PHP_SELF'];?>";
 } 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." )";

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

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by: