Mik*_*sen 77 javascript timezone
我知道如何获得时区偏移,但我需要的是能够检测"美国/纽约"之类的东西.这甚至可能来自JavaScript还是我将不得不根据偏移量进行猜测?
Dan*_*ton 152
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)Run Code Online (Sandbox Code Playgroud)
请记住,在支持Internationalization API的某些较旧的浏览器版本中,timeZone属性设置为undefined而不是用户的时区字符串.据我所知,在撰写本文时(2017年7月),除IE11之外的所有当前浏览器都会将用户时区作为字符串返回.
mrn*_*ver 35
大多数赞成的答案可能是获取时区的最佳方法,但是,Intl.DateTimeFormat().resolvedOptions().timeZone根据定义返回 IANA 时区名称,该名称是英文的。
如果您想要当前用户语言的时区名称,您可以从Date的字符串表示中解析它,如下所示:
function getTimezoneName() {
const today = new Date();
const short = today.toLocaleDateString(undefined);
const full = today.toLocaleDateString(undefined, { timeZoneName: 'long' });
// Trying to remove date from the string in a locale-agnostic way
const shortIndex = full.indexOf(short);
if (shortIndex >= 0) {
const trimmed = full.substring(0, shortIndex) + full.substring(shortIndex + short.length);
// by this time `trimmed` should be the timezone's name with some punctuation -
// trim it from both sides
return trimmed.replace(/^[\s,.\-:;]+|[\s,.\-:;]+$/g, '');
} else {
// in some magic case when short representation of date is not present in the long one, just return the long one as a fallback, since it should contain the timezone's name
return full;
}
}
console.log(getTimezoneName());Run Code Online (Sandbox Code Playgroud)
在 Chrome 和 Firefox 中测试。
当然,这在某些环境中不会按预期工作。例如,node.js 返回 GMT 偏移量(例如GMT+07:00)而不是名称。但我认为它仍然可以作为后备阅读。
PS 在 IE11 中不起作用,就像Intl...解决方案一样。
小智 28
当前用户语言的结果的简短可能性:
console.log(new Date().toLocaleDateString(undefined, {day:'2-digit',timeZoneName: 'long' }).substring(4));Run Code Online (Sandbox Code Playgroud)
您可以使用此脚本. http://pellepim.bitbucket.org/jstz/
在这里分叉或克隆存储库. https://bitbucket.org/pellepim/jstimezonedetect
包含脚本后,您可以在 - jstz.olson.timezonesvariable中获取时区列表 .
以下代码用于确定客户端浏览器的时区.
var tz = jstz.determine();
tz.name();
Run Code Online (Sandbox Code Playgroud)
享受jstz!
Ome*_*er 6
按名称检索时区(即“美国/纽约”)
moment.tz.guess();
Run Code Online (Sandbox Code Playgroud)
您可以使用此处的映射表简单地编写自己的代码: http://www.timeanddate.com/time/zones/
或者,使用 moment-timezone 库: http: //momentjs.com/timezone/docs/
看zone.name; // America/Los_Angeles
或者,这个库: https: //github.com/Canop/tzdetect.js
| 归档时间: |
|
| 查看次数: |
68246 次 |
| 最近记录: |