我知道如何获得时区偏移,但我需要的是检测“美国/纽约”之类内容的能力。JavaScript能做到吗,还是我只能根据偏移量来估计?
当前回答
要检测像“America/New York.”这样的内容,可以使用Luxon库中的新LocalZone()。
import { LocalZone } from 'luxon';
const zoneName = new LocalZone().name;
其他回答
国际化API支持获取用户时区,当前所有浏览器都支持该API。
控制台日志(Intl DateTimeFormat resolvedOptions()()。timeZone)
请记住,在一些支持国际化API的旧浏览器版本上,timeZone属性被设置为未定义,而不是用户的时区字符串。据我所知,在撰写本文时(2017年7月),除IE11之外的所有当前浏览器都将以字符串形式返回用户时区。
在javascript中,Date.getTimezoneOffset()方法返回当前地区相对于UTC的时区偏移,单位为分钟。
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
时刻时区将是一个有用的工具。 http://momentjs.com/timezone/
在时区之间转换日期
var newYork = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london = newYork.clone().tz("Europe/London");
newYork.format(); // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format(); // 2014-06-01T17:00:00+01:00
如果你已经在使用Moment.js,你可以猜出时区名称:
moment.tz.guess(); // eg. "America/New York"
要检测像“America/New York.”这样的内容,可以使用Luxon库中的新LocalZone()。
import { LocalZone } from 'luxon';
const zoneName = new LocalZone().name;
获得最多好评的答案可能是获取时区的最佳方法,然而,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…解决方案。
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法