admin管理员组文章数量:1390812
I am using jsTimezoneDetect script to detect user current timezone. Code below display result as America/Chicago
. Is there a way to display CDT
/CST
(depending on today date)?
var timezone = jstz.determine();
timezone.name();
Or is there any other script I can use?
I am using jsTimezoneDetect script to detect user current timezone. Code below display result as America/Chicago
. Is there a way to display CDT
/CST
(depending on today date)?
var timezone = jstz.determine();
timezone.name();
Or is there any other script I can use?
Share Improve this question asked May 22, 2015 at 16:34 αƞjiβαƞjiβ 3,26615 gold badges63 silver badges104 bronze badges2 Answers
Reset to default 9First understand:
- A time zone abbreviation is potentially ambiguous (5 different CST's).
- Not all time zones have meaningful abbreviations. Some are just made up to plete the API, but not actually used by people in the region (MSK in Belarus).
- There are often disagreements about the correct abbreviation to use (HST vs HAST).
- They are usually in English, though other languages may have different abbreviations for the same time zone. (PST vs HNP (French))
- The abbreviation depends highly on the specific date chosen - as it could change for daylight saving time (EST vs EDT).
In many browsers, you can get the abbreviation directly (via ECMA-402) by:
const d = new Date(); // now, or the specific date in question
const tz = d.toLocaleString('en', {timeZoneName: 'short'}).split(' ').pop();
console.log(tz);
This doesn't necessarily work everywhere though.
Since you're working with jsTimeZoneDetect, you already have an IANA time zone identifier ("America/Chicago"). So, you could get it from moment-timezone, like this:
var m = moment(); // now, or the moment in question
var s = m.tz('America/Chicago').format('z');
That will work everywhere, but you have the overhead of moment and moment-timezone, and jstz, which is probably overkill unless you are using these libraries for other purposes anyway.
You might also consider a server-side solution. For example, if you're using PHP, you can use this code. Or, if you're using .NET, you can use my TimeZoneNames library.
In native JS you could:
var d = new Date();
timezone = d.getTimezoneOffset();
and then go over it with a switch.
本文标签: javascriptDisplay three letters time zone code using jsTimezoneDetect scriptStack Overflow
版权声明:本文标题:javascript - Display three letters time zone code using jsTimezoneDetect script - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744752861a2623284.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论