使用 JavaScript 检测时区缩写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1954397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect timezone abbreviation using JavaScript
提问by Stephen Sorensen
I need a way to detect the timezone of a given date object. I do NOT want the offset, nor do I want the full timezone name. I need to get the timezone abbreviation.
我需要一种方法来检测给定日期对象的时区。我不想要偏移量,也不想要完整的时区名称。我需要获取时区缩写。
For example, GMT, UTC, PST, MST, CST, EST, etc...
例如,GMT、UTC、PST、MST、CST、EST 等...
Is this possible? The closest I've gotten is parsing the result of date.toString(), but even that won't give me an abbreviation. It gives me the timezone's long name.
这可能吗?我得到的最接近的是解析 的结果date.toString(),但即使这样也不会给我一个缩写。它给了我时区的长名称。
采纳答案by Andy West
If all else fails, you can simply create your own hashtable with the long names and abbreviations.
如果所有其他方法都失败了,您可以简单地使用长名称和缩写创建自己的哈希表。
回答by Stephen DuMont
A native solution:
原生解决方案:
var zone = new Date().toLocaleTimeString('en-us',{timeZoneName:'short'}).split(' ')[2]
console.log(zone)
回答by absynce
moment-timezoneincludes an undocumented method .zoneAbbr()which returns the time zone abbreviation. This also requires a set of rules which are available to select and download as needed.
moment-timezone包括一个未记录的方法.zoneAbbr(),该方法返回时区缩写。这还需要一组规则,可根据需要选择和下载。
Doing this:
这样做:
<script src="moment.js"></script>
<script src="moment-timezone.js"></script>
<script src="moment-timezone-data.js"></script>
<script>
moment().tz("America/Los_Angeles").zoneAbbr();
</script>
Returns:
返回:
'PDT' // As of this posting.
Edit (Feb 2018)
编辑(2018 年 2 月)
Evan Czaplicki has worked on a draft proposal to add a time zone API to browsers.
Evan Czaplicki 已经起草了一份向浏览器添加时区 API 的提案草案。
回答by Diego125k
[sorry for how I write English]
[对不起我写英语的方式]
Hi, date object doesn't have a method for get the timezone abreviation, but it is implicit there at almost end of the toString return:
嗨,日期对象没有获取时区缩写的方法,但它在 toString 返回几乎结束时隐含在那里:
for example
例如
var rightNow = new Date();
alert(rightNow);
the output will be something like "Wed Mar 30 2011 17:29:16 GMT-0300 (ART)" so, you can isolate what is between parentheses "ART" that is the timezone abreviation
输出将类似于“Wed Mar 30 2011 17:29:16 GMT-0300 (ART)”,因此,您可以隔离括号“ART”之间的内容,即时区缩写
var rightNow = new Date();
alert(String(String(rightNow).split("(")[1]).split(")")[0]);
the output will be "ART"
输出将是“ART”
it's to late to answer, but I hope it'll be usefull for somebody
现在回答为时已晚,但我希望它对某人有用
回答by Charlie
This works perfectly in Chrome, Firefox but only mostly in IE11. In IE11, timezones without straight forward abbreviations like "Indian Chagos Time" will return "ICT" instead of the proper "IOT"
这在 Chrome、Firefox 中完美运行,但主要在 IE11 中运行。在 IE11 中,没有像“Indian Chagos Time”这样的直接缩写的时区将返回“ICT”而不是正确的“IOT”
var result = "unknown";
try{
// Chrome, Firefox
result = /.*\s(.+)/.exec((new Date()).toLocaleDateString(navigator.language, { timeZoneName:'short' }))[1];
}catch(e){
// IE, some loss in accuracy due to guessing at the abbreviation
// Note: This regex adds a grouping around the open paren as a
// workaround for an IE regex parser bug
result = (new Date()).toTimeString().match(new RegExp("[A-Z](?!.*[\(])","g")).join('');
}
console.log(result);
Result:
结果:
"CDT"
回答by vineeth61
I was able to achieve this with only moment.
我只用了片刻就实现了这一目标。
moment.tz(moment.tz.guess()).zoneAbbr() //IST
回答by Jordan
Updated for 2015:
2015 年更新:
jsTimezoneDetectcan be used together with moment-timezoneto get the timezone abbreviation client side:
jsTimezoneDetect可以与moment-timezone一起使用来获取时区缩写客户端:
moment.tz(new Date(), jstz.determine().name()).format('z'); //"UTC"
Moment-timezone cannot do this on it's own as its function which used to handle this was depreciated because it did not work under all circumstances: https://github.com/moment/moment/issues/162to get the timezone abbreviation client side.
Moment-timezone 无法自行执行此操作,因为它用于处理此问题的功能已贬值,因为它在所有情况下都不起作用:https: //github.com/moment/moment/issues/162获取时区缩写客户端.
回答by Renato
For a crossbrowsersupport I recommend using YUI 3 Library:
对于跨浏览器支持,我建议使用 YUI 3 库:
Y.DataType.Date.format(new Date(), {format:"%Z"});
It supports strftimeidentifiers.
它支持strftime标识符。
For more information: http://yuilibrary.com/yui/docs/datatype/#dates
更多信息:http: //yuilibrary.com/yui/docs/datatype/#dates
回答by Gary
I know the problem remains of differences between browsers, but this is what I used to get in Chrome. However it is still not an abbreviation because Chrome returns the long name.
我知道问题仍然是浏览器之间的差异,但这就是我以前在 Chrome 中遇到的问题。但是它仍然不是缩写,因为 Chrome 返回长名称。
new Date().toString().replace(/^.*GMT.*\(/, "").replace(/\)$/, "")
回答by Will Schoenberger
This is a tricky subject. From what I gather the timezone is not embedded as part of the Date object when it's created. You also cannot set the timezone for a Date object. However, there is a timezone offset you can get from a Date object which is determined by the user's host system (timezone) settings. Think of timezone as a way to determine the offset from UTC.
这是一个棘手的话题。据我所知,时区在创建时没有嵌入为 Date 对象的一部分。您也不能为 Date 对象设置时区。但是,您可以从 Date 对象获得时区偏移量,该偏移量由用户的主机系统(时区)设置确定。将时区视为确定与 UTC 偏移量的一种方式。
To make life easier, I highly recommend momentand moment-timezonefor handling these things. Moment creates a wrapper object for Datewith a nice API for all kinds of things.
为了让生活更轻松,我强烈推荐moment并moment-timezone处理这些事情。MomentDate为各种事物创建了一个具有良好 API的包装器对象。
If an existing date object is supplied to you through some parameter or something, you can pass it the constructor when creating a the moment object and you're ready to roll. At this point you can use moment-timezoneto guess the user's timezone name, and then use moment-timezone formattingto get the abbreviation for the timezone. I would venture to say that most users have their timezone set automatically but you shouldn't rely on this for 100% accuracy. If needed you can also set the timezone you want to use manually before pulling the format you need.
如果现有的日期对象通过某个参数或其他东西提供给您,您可以在创建时刻对象时将其传递给构造函数,然后您就可以开始使用了。此时可以使用moment-timezone猜测用户的时区名称,然后使用moment-timezone格式来获取时区的缩写。我敢说,大多数用户的时区是自动设置的,但您不应该依赖于 100% 的准确性。如果需要,您还可以在提取所需格式之前手动设置要使用的时区。
In general when working with date and time it's best to store UTC in your database and then use moment js to format the time for the user's timezone when displaying it. There may be cases where you need to be sure the timezone is correct. For example if you are allowing a user to schedule something for a specific date and time. You would need to make absolutely sure that with a west coast user that you set the timezone to PDT/PST before converting to UTC for storage in your database.
通常,在处理日期和时间时,最好将 UTC 存储在您的数据库中,然后在显示时使用 moment js 来格式化用户时区的时间。在某些情况下,您可能需要确保时区正确。例如,如果您允许用户在特定日期和时间安排某事。在转换为 UTC 以存储在数据库中之前,您需要绝对确保与西海岸用户一起将时区设置为 PDT/PST。
Regarding the timezone abbreviation...
Here is a basic example to get the timezone abbreviation using moment and moment-timezone.
关于时区缩写...
这是使用moment和moment-timezone获取时区缩写的基本示例。
// if all you need is the user's timezone abbreviation you don't even need a date object.
const usersTimezoneName = moment.tz.guess()
const timezoneAbbr = moment().tz(usersTimezoneName).format('z')
console.log(timezoneAbbr) // PST (depending on where the user is)
// to manually set the timezone
const newYorkAbbr = moment(dateObj).tz('America/New_York').format('z')
console.log(newYorkAbbr) // EST
For displaying a specific date object with offsets for a specific timezone you can do this.
要显示具有特定时区偏移量的特定日期对象,您可以执行此操作。
const xmas = new Date('December 25, 2017 16:20:00')
const losAngelesXmas = moment(xmas).tz('America/Los_Angeles')
console.log(losAngelesXmas.format("dddd, MMMM Do YYYY, h:mm:ss a")) // Monday, December 25th 2017, 4:20:00 pm

