Determine a user's timezone

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

    I still have not seen a detailed answer here that gets the time zone. You shouldn't need to geocode by IP address or use PHP (lol) or incorrectly guess from an offset.

    Firstly a time zone is not just an offset from GMT. It is an area of land in which the time rules are set by local standards. Some countries have daylight savings, and will switch on DST at differing times. It's usually important to get the actual zone, not just the current offset.

    If you intend to store this timezone, for instance in user preferences you want the zone and not just the offset. For realtime conversions it won't matter much.

    Now, to get the time zone with javascript you can use this:

    >> new Date().toTimeString();
    "15:46:04 GMT+1200 (New Zealand Standard Time)"
    //Use some regular expression to extract the time.
    

    However I found it easier to simply use this robust plugin which returns the Olsen formatted timezone:

    https://github.com/scottwater/jquery.detect_timezone

提交回复
热议问题