Determine a user's timezone

前端 未结 25 2932
刺人心
刺人心 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:36

    First, understand that time zone detection in JavaScript is imperfect. You can get the local time zone offset for a particular date and time using getTimezoneOffset on an instance of the Date object, but that's not quite the same as a full IANA time zone like America/Los_Angeles.

    There are some options that can work though:

    • Most modern browsers support IANA time zones in their implementation of the ECMAScript Internationalization API, so you can do this:

    const tzid = Intl.DateTimeFormat().resolvedOptions().timeZone;
    console.log(tzid);

    The result is a string containing the IANA time zone setting of the computer where the code is running.

    Supported environments are listed in the Intl compatibility table. Expand the DateTimeFormat section, and look at the feature named resolvedOptions().timeZone defaults to the host environment.

    • Some libraries, such as Luxon use this API to determine the time zone through functions like luxon.Settings.defaultZoneName.

    • If you need to support an wider set of environments, such as older web browsers, you can use a library to make an educated guess at the time zone. They work by first trying the Intl API if it's available, and when it's not available, they interrogate the getTimezoneOffset function of the Date object, for several different points in time, using the results to choose an appropriate time zone from an internal data set.

      Both jsTimezoneDetect and moment-timezone have this functionality.

        // using jsTimeZoneDetect
        var tzid = jstz.determine().name();
      
        // using moment-timezone
        var tzid = moment.tz.guess();
      

      In both cases, the result can only be thought of as a guess. The guess may be correct in many cases, but not all of them.

      Additionally, these libraries have to be periodically updated to counteract the fact that many older JavaScript implementations are only aware of the current daylight saving time rule for their local time zone. More details on that here.

    Ultimately, a better approach is to actually ask your user for their time zone. Provide a setting that they can change. You can use one of the above options to choose a default setting, but don't make it impossible to deviate from that in your app.

    There's also the entirely different approach of not relying on the time zone setting of the user's computer at all. Instead, if you can gather latitude and longitude coordinates, you can resolve those to a time zone using one of these methods. This works well on mobile devices.

提交回复
热议问题