Get user timezone string with Javascript / PHP?

后端 未结 4 1377
猫巷女王i
猫巷女王i 2020-12-06 08:07

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

4条回答
  •  一整个雨季
    2020-12-06 08:38

    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

提交回复
热议问题