我知道如何获得时区偏移,但我需要的是检测“美国/纽约”之类内容的能力。JavaScript能做到吗,还是我只能根据偏移量来估计?
当前回答
用当前用户的语言表示结果的简短可能性:
console.log(新日期()。toLocaleDateString(未定义,{day:'2-digit',timeZoneName: 'long'}).substring(4));
其他回答
国际化API支持获取用户时区,当前所有浏览器都支持该API。
控制台日志(Intl DateTimeFormat resolvedOptions()()。timeZone)
请记住,在一些支持国际化API的旧浏览器版本上,timeZone属性被设置为未定义,而不是用户的时区字符串。据我所知,在撰写本文时(2017年7月),除IE11之外的所有当前浏览器都将以字符串形式返回用户时区。
用当前用户的语言表示结果的简短可能性:
console.log(新日期()。toLocaleDateString(未定义,{day:'2-digit',timeZoneName: 'long'}).substring(4));
console.log(新日期()。toLocaleDateString(undefined, {day:'2-digit',timeZoneName: 'long'}).substring(4).match(/\b(\w)/g).join("))
你可以使用下面的映射表来编写自己的代码: http://www.timeanddate.com/time/zones/
或者,使用moment-timezone库: http://momentjs.com/timezone/docs/
看到zone.name;/ /美国/ Los_Angeles
或者,这个库: https://github.com/Canop/tzdetect.js
获得最多好评的答案可能是获取时区的最佳方法,然而,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());
在Chrome和Firefox中测试。
当然,在某些环境中,这不会像预期的那样工作。例如,node.js返回一个GMT偏移量(例如GMT+07:00)而不是一个名称。但我认为作为备用方案还是有可读性的。
P.S.不会在IE11中工作,就像Intl…解决方案。
推荐文章
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 在c#中创建一个特定时区的DateTime
- 反应钩子-正确的方式清除超时和间隔
- TypeScript枚举对象数组
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式
- onClick ReactJS调用多个函数
- 如何在JavaScript中转义单引号(')?
- Ng-repeat结束事件
- 谷歌MAP API未捕获的类型错误:无法读取属性“offsetWidth”为空
- 模糊vs聚焦-有什么真正的区别吗?
- 如何使用JavaScript创建和样式一个div ?