如何在JavaScript中获取时区名称

How can I get the timezone name in JavaScript?

本文关键字:时区 获取 JavaScript      更新时间:2023-09-26

我知道如何获得时区偏移量,但我需要的是检测类似"美国/纽约"的东西的能力。这甚至可以从JavaScript中实现吗?还是我必须根据偏移量进行猜测?

国际化API支持获取用户时区,目前所有浏览器都支持。

console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)

请记住,在某些支持国际化API的较旧浏览器版本上,timeZone属性设置为undefined,而不是用户的时区字符串。据我所知,在撰写本文时(2017年7月),除IE11外,所有当前浏览器都将以字符串形式返回用户时区。

大多数投票支持的答案可能是获得时区的最佳方式,然而,Intl.DateTimeFormat().resolvedOptions().timeZone根据定义返回IANA时区名称,该名称是英文的。

如果您想要当前用户语言中的时区名称,您可以从Date的字符串表示中解析它,如下所示:

function getTimezoneName() {
  const today = new Date();
  const short = today.toLocaleDateString(undefined);
  const full = today.toLocaleDateString(undefined, { timeZoneName: 'long' });
  // Trying to remove date from the string in a locale-agnostic way
  const shortIndex = full.indexOf(short);
  if (shortIndex >= 0) {
    const trimmed = full.substring(0, shortIndex) + full.substring(shortIndex + short.length);
    
    // by this time `trimmed` should be the timezone's name with some punctuation -
    // trim it from both sides
    return trimmed.replace(/^['s,.'-:;]+|['s,.'-:;]+$/g, '');
  } else {
    // in some magic case when short representation of date is not present in the long one, just return the long one as a fallback, since it should contain the timezone's name
    return full;
  }
}
console.log(getTimezoneName());

在Chrome和Firefox中测试。

当然,这在某些环境中不会按预期工作。例如,node.js返回GMT偏移量(例如GMT+07:00),而不是名称。但我认为,作为后备方案,它仍然可读。

p.S.在IE11中不起作用,就像Intl...解决方案一样。

以当前用户的语言生成结果的可能性很小:

console.log(new Date().toLocaleDateString(undefined, {day:'2-digit',timeZoneName: 'long' }).substring(4));

如果您已经在使用Moment.js,您可以猜测时区名称:

moment.tz.guess(); // eg. "America/New York"

您可以使用此脚本。http://pellepim.bitbucket.org/jstz/

在此处分叉或克隆存储库。https://bitbucket.org/pellepim/jstimezonedetect

一旦包含了脚本,就可以在-jstz.olson.timezones变量中获得时区列表。

下面的代码用于确定客户端浏览器的时区。

var tz = jstz.determine();
tz.name();

享受jstz!

console.log(new Date().toLocaleDateString(undefined, {day:'2-digit',timeZoneName: 'long' }).substring(4).match(/'b('w)/g).join(''))

您只需使用此处的映射表即可编写自己的代码:http://www.timeanddate.com/time/zones/

或者,使用时刻时区库:http://momentjs.com/timezone/docs/

参见zone.name; // America/Los_Angeles

或者,此库:https://github.com/Canop/tzdetect.js

检测类似于"美国/纽约&";,您可以使用Luxon库中的new LocalZone()

import { LocalZone } from 'luxon';
const zoneName = new LocalZone().name;

这将获得旧javascript中的时区代码(例如GMT)(我使用的是带有旧引擎的谷歌应用程序脚本):

function getTimezoneName() {
  return new Date().toString().get(/'((.+)')/);
}

我只是把这个放在这里,以防有人需要。

在javascript中,Date.getTimezoneOffset()方法返回当前区域设置的时区偏移量(以分钟为单位)。

var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;

Moment'时区将是一个有用的工具。http://momentjs.com/timezone/

在时区之间转换日期

var newYork    = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london     = newYork.clone().tz("Europe/London");
newYork.format();    // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format();     // 2014-06-01T17:00:00+01:00