Is there a reliable way to get a timezone from client browser? I saw the following links but I want a more robust solution.
相关问题
- Angular RxJS mergeMap types
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
I used an approach similar to the one taken by Josh Fraser, which determines the browser time offset from UTC and whether it recognizes DST or not (but somewhat simplified from his code):
Upon loading, the
ClientTZ.getBrowserTZ()
function is executed, which sets:ClientTZ.UTCoffset
to the browser time offset from UTC in minutes (e.g., CST is −360 minutes, which is −6.0 hours from UTC);ClientTZ.UTCoffsetT
to the offset in the form'±hhmmD'
(e.g.,'-0600D'
), where the suffix isD
for DST andS
for standard (non-DST);ClientTZ.hasDST
(to true or false).The
ClientTZ.UTCoffset
is provided in minutes instead of hours, because some timezones have fractional hourly offsets (e.g., +0415).The intent behind
ClientTZ.UTCoffsetT
is to use it as a key into a table of timezones (not provided here), such as for a drop-down<select>
list.Half a decade later we have a built-in way for it! For modern browsers I would use:
It may not work for the browser you need to support, if that is the case I would fall back to one of the libraries presented on the previous answers.
Does not work on firefox (51 and below) and IE https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/resolvedOptions#Browser_compatibility
you could use moment-timezone to guess the timezone:
Often when people are looking for "timezones", what will suffice is just "UTC offset". e.g., their server is in UTC+5 and they want to know that their client is running in UTC-8.
In plain old javascript
(new Date()).getTimezoneOffset()/60
will return the current number of hours offset from UTC.It's worth noting a possible "gotcha" in the sign of the
getTimezoneOffset()
return value (from MDN docs):However, I recommend you use the moment.js for time/date related Javascript code. In which case you can get an ISO 8601 formatted UTC offset by running:
(It probably bears mentioning that the client can easily falsify this information.)
Here is a jsfiddle
It provides the abbreviation of the current user timezone.
Here is the code sample
Look at this repository pageloom it is helpful
download jstz.min.js and add a function to your html page
and call this function from your display tag