αƞj*_*jiβ 3 javascript jquery timezone datetime jstimezonedetect
我正在使用jsTimezoneDetect脚本来检测用户当前时区。下面的代码将结果显示为America/Chicago. 有没有办法显示CDT/ CST(取决于今天的日期)?
var timezone = jstz.determine();
timezone.name();
Run Code Online (Sandbox Code Playgroud)
或者我可以使用任何其他脚本吗?
首先了解:
在许多浏览器中,您可以通过以下方式直接获取缩写(通过ECMA-402):
const d = new Date(); // now, or the specific date in question
const tz = d.toLocaleString('en', {timeZoneName: 'short'}).split(' ').pop();
console.log(tz);Run Code Online (Sandbox Code Playgroud)
但这不一定适用于所有地方。
由于您正在使用 jsTimeZoneDetect,因此您已经拥有 IANA 时区标识符(“美国/芝加哥”)。因此,您可以从moment-timezone获取它,如下所示:
var m = moment(); // now, or the moment in question
var s = m.tz('America/Chicago').format('z');
Run Code Online (Sandbox Code Playgroud)
这将适用于任何地方,但是您有时刻和时刻时区以及 jstz 的开销,除非您将这些库用于其他目的,否则这可能是过度的。
您也可以考虑使用服务器端解决方案。例如,如果您使用的是 PHP,则可以使用此代码。或者,如果您使用 .NET,您可以使用我的TimeZoneNames库。
| 归档时间: |
|
| 查看次数: |
2379 次 |
| 最近记录: |