[英]How to display the abbreviated name of the user's timezone (not GMT offset) in JavaScript?
I tried something like this: 我尝试过这样的事情:
function set_local_time(utcSeconds) {
var d = new Date(0); // The 0 sets the date to the epoch
d.setUTCSeconds(utcSeconds); //update date object with utcSeconds
return d.toLocaleTimeString() + ', ' + d.toLocaleDateString() + ' ' + d.toLocaleTimeString('en-us',{timeZoneName:'short'}).split(' ')[2] //time, date timezone
}
Which takes the time and converts it into the user's local time. 这将花费时间并将其转换为用户的本地时间。 It works perfectly within the USA (it displays
PDT
, EDT
, etc.), but outside the USA, it just displays the GMT offset (eg GMT+1
, GMT+8
, etc.). 它在美国境内完美运行(显示
PDT
, EDT
等),但是在美国以外,仅显示GMT偏移量(例如GMT+1
, GMT+8
等)。
Is there a way to display the abbreviated name of the user's timezone internationally? 有没有办法在国际上显示用户时区的缩写名称? So instead of
GMT+1
for London, it would display BST
instead? 因此,它会显示
BST
而不是伦敦的GMT+1
?
You can't get this information directly from a Date
object, but you can get it from the Intl.DateTimeFormat().resolvedOptions() interface like this: 您不能直接从
Date
对象获取此信息,但可以从Intl.DateTimeFormat()。resolvedOptions()接口获取该信息,如下所示:
let tz = Intl.DateTimeFormat().resolvedOptions().timeZone; console.log(tz);
This will give you the canonical name of the local time zone (eg America/New_York). 这将为您提供当地时区的规范名称(例如America / New_York)。 If you want to map the time zone to an abbreviation including daylight savings time (eg EST, EDT, PST, EST) your best bet is to use a library like moment-timezone .
如果要将时区映射到包括夏时制的缩写(例如EST,EDT,PST,EST),则最好的选择是使用诸如moment-timezone之类的库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.