Saq*_*Ali 5 javascript timezone
我想在我的网页上显示用户 Timezone的全名。例如:
Eastern Standard Time (North America)
Pacific Daylight Time (North America)
West Africa Time
Run Code Online (Sandbox Code Playgroud)
我怎样才能在 Javascript 中做到这一点?我见过呈现如下内容的解决方案:America/New_York. 但这并不是我真正要寻找的。
edd*_*P23 16
一个班轮:
new window.Intl.DateTimeFormat().resolvedOptions().timeZone
Run Code Online (Sandbox Code Playgroud)
您似乎要求在当前时间点以用户的当前语言对用户的当前时区进行人类可读的描述。
在大多数完全支持ECMAScript 国际化 API 的现代浏览器和其他环境中,最好按如下方式提取:
// Get a specific point in time (here, the current date/time):
const d = new Date();
// Get a DateTimeFormat object for the user's current culture (via undefined)
// Ask specifically for the long-form of the time zone name in the options
const dtf = Intl.DateTimeFormat(undefined, {timeZoneName: 'long'});
// Format the date to parts, and pull out the value of the time zone name
const result = dtf.formatToParts(d).find((part) => part.type == 'timeZoneName').value;
Run Code Online (Sandbox Code Playgroud)
例如,在我冬天在 Windows 上的 Chrome 79 浏览器中,它返回“太平洋标准时间”。夏季相同的代码将返回“太平洋夏令时”。如果要反映在一年中的特定时间生效的时区描述,请在该特定时间创建Date对象。
在不支持IntlAPI 的旧环境中,您可以尝试从Date.toString输出中提取部分时区名称,如下所示:
var s = new Date().toString().match(/\((.*)\)/).pop();
Run Code Online (Sandbox Code Playgroud)
这只是因为对象toString上函数的输出由Date实现来定义,并且许多实现碰巧在括号中提供时区,如下所示:
Sun Feb 21 2016 22:11:00 GMT-0800 (Pacific Standard Time)
Run Code Online (Sandbox Code Playgroud)
如果您正在寻找通用名称,例如简单的“太平洋时间” - 抱歉,这不可用。
| 归档时间: |
|
| 查看次数: |
14123 次 |
| 最近记录: |