Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get user timezone string with Javascript / PHP?

Tags:

timezone

php

I'm trying to get the user's timezone as a string on singup. example:

$timezone = "Asia/Tel_Aviv";

While researching the issue, I got how to Get timezone offset with Javascript, but I'm still unclear about how can I translate the timezone offset to a timezone string in php, as shown above?

Or, which other method cas I use in Javascript / PHP for getting the timezone string for each user?

I'm really not sure how to approach this.

like image 584
Roy Avatar asked Dec 01 '22 20:12

Roy


2 Answers

You can't do this in PHP alone.

You can use Javascript to set the value in a cookie, then use PHP to read the cookie on the next page (re)load.

Javascript:

var dateVar = new Date()
var offset = dateVar.getTimezoneOffset();
document.cookie = "offset="+offset;

PHP:

echo $_COOKIE['offset'];

Use this to convert the offset to the friendly timezone name in PHP. Javascript returns the offset in minutes, while this PHP function expects the input to be in seconds - so multiply by 60. The third parameter is a boolean value of whether or not you are in Daylight Savings Time. Read the manual and update the code to fit your needs.

echo timezone_name_from_abbr("", intval($_COOKIE['offset'])*60, 0);

http://php.net/manual/en/function.timezone-name-from-abbr.php

like image 90
Nick Pickering Avatar answered Dec 10 '22 17:12

Nick Pickering


  1. You cannot get the timezone name from an offset. That's because there are many timezones which have the same offset at any given time, so you can't pick one based on an offset. (If you do, this will bite you in the butt later when the timezone goes into or out of DST, changing the offset.
  2. Your best bet is to do geolocation by IP address (google it, lots of material out there) as a best first guess and then give the user an option to choose his timezone himself.
like image 45
deceze Avatar answered Dec 10 '22 17:12

deceze