Determine a user's timezone

前端 未结 25 2939
刺人心
刺人心 2020-11-21 07:12

Is there a standard way for a web server to be able to determine a user\'s timezone within a web page?

Perhaps from an HTTP header or part of the user-agent

25条回答
  •  别跟我提以往
    2020-11-21 07:40

    It is simple with JavaScript and PHP:

    Even though the user can mess with his/her internal clock and/or timezone, the best way I found so far, to get the offset, remains new Date().getTimezoneOffset();. It's 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 the database
    $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, you 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.

提交回复
热议问题