我知道如何获得时区偏移,但我需要的是检测“美国/纽约”之类内容的能力。JavaScript能做到吗,还是我只能根据偏移量来估计?
当前回答
您可以使用这个脚本。 http://pellepim.bitbucket.org/jstz/
在这里分叉或克隆存储库。 https://bitbucket.org/pellepim/jstimezonedetect
一旦包含了脚本,就可以在- jstz.olson.timezones variable中获得时区列表。
下面的代码用于确定客户端浏览器的时区。
var tz = jstz.determine();
tz.name();
享受jstz !
其他回答
你可以使用下面的映射表来编写自己的代码: http://www.timeanddate.com/time/zones/
或者,使用moment-timezone库: http://momentjs.com/timezone/docs/
看到zone.name;/ /美国/ Los_Angeles
或者,这个库: https://github.com/Canop/tzdetect.js
console.log(新日期()。toLocaleDateString(undefined, {day:'2-digit',timeZoneName: 'long'}).substring(4).match(/\b(\w)/g).join("))
要检测像“America/New York.”这样的内容,可以使用Luxon库中的新LocalZone()。
import { LocalZone } from 'luxon';
const zoneName = new LocalZone().name;
您可以使用这个脚本。 http://pellepim.bitbucket.org/jstz/
在这里分叉或克隆存储库。 https://bitbucket.org/pellepim/jstimezonedetect
一旦包含了脚本,就可以在- jstz.olson.timezones variable中获得时区列表。
下面的代码用于确定客户端浏览器的时区。
var tz = jstz.determine();
tz.name();
享受jstz !
国际化API支持获取用户时区,当前所有浏览器都支持该API。
控制台日志(Intl DateTimeFormat resolvedOptions()()。timeZone)
请记住,在一些支持国际化API的旧浏览器版本上,timeZone属性被设置为未定义,而不是用户的时区字符串。据我所知,在撰写本文时(2017年7月),除IE11之外的所有当前浏览器都将以字符串形式返回用户时区。