如何在JavaScript中获取时区名称?

232

我知道如何获取时区偏移量,但我需要的是能够检测到类似于“美国/纽约”的内容。这是否可能通过JavaScript实现,还是我需要根据偏移量进行猜测?


2
这是Jon Nylander编写的一个函数,也许它会有所帮助 https://bitbucket.org/pellepim/jstimezonedetect - yunzen
这里有一个相关的答案或许可以帮助你:https://dev59.com/TmIk5IYBdhLWcg3wRcUo#19421672 - Douglas
这个回答解决了你的问题吗?在JavaScript中获取客户端的时区(和偏移量) - undefined
10个回答

481

国际化 API 支持获取用户的时区信息,并且在所有当前浏览器中都得到支持

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

请注意,在一些支持国际化 API 的旧版浏览器上,timeZone 属性设置为 undefined 而不是用户的时区字符串。据我所知,截至撰写本文时(2017 年 7 月),除了 IE11 外的所有当前浏览器 都会返回用户时区作为字符串。

2
在Firefox中返回undefinedlet timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; - ViaTech
2
let anything will return undefined, you need to evaluate timezone, or only run Intl.DateTimeFormat().resolvedOptions().timeZone - Daniel Compton

58
最受欢迎的答案可能是获取时区的最佳方法,然而,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)而不是名称。但我认为作为备选方案,它仍然可读。
附注:在IE11中不起作用,就像Intl...解决方案一样。

这是一个很好的解决方案。我正在使用 timeZoneName: 'short' 来获取简短形式,如 EST 或 GMT+0230,我可以在 Java 后端中使用。 - John Yeary

26

当前用户语言的简短可能结果:

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


2
我认为这个例子是最用户友好的,因为用户可能不在其他例子返回的城市中。对于只寻找缩写(如PDTEST)的人,您可以使用此变体: new Date().toLocaleDateString(undefined, {day:'2-digit',timeZoneName: 'short' }).substring(4) - ninapavlich

9
如果您已经在使用Moment.js,您可以猜测时区名称:
moment.tz.guess(); // eg. "America/New York"

50
请注意,这也可以简单地在没有任何依赖关系的情况下完成: Intl.DateTimeFormat().resolvedOptions().timeZone - user2923322
5
没错,虽然 moment-js 也会为不支持该功能的“浏览器”猜测时区。 :) - Ferran Maylinch
8
在IE11中,Intl.DateTimeFormat().resolvedOptions().timeZone返回undefined,但moment.tz.guess()返回正确的值。 - Antoni4

5

1

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


2
这非常脆弱,当浏览器语言不是英语时会出现错误。 - bmaupin

0

10
由于多个时区具有相同的偏移量,因此此信息并不特别有用。 - bmerigan

-3

要检测类似于 "America/New York." 这样的内容,你可以使用 Luxon 库 中的 new LocalZone() 方法。

import { LocalZone } from 'luxon';

const zoneName = new LocalZone().name;

这个在浏览器中不起作用,只能在Node.js中使用。 - Konstantin Möllers

-4
这是关于编程的内容,以下是翻译:

在旧版 JavaScript 中获取时区代码(例如 GMT)(我正在使用带有旧引擎的 Google 应用脚本):

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

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


1
我认为这仅适用于UTC/GMT。其他时区似乎是全拼的,例如太平洋夏令时 - Ian Dunn

-5
在 JavaScript 中,Date.getTimezoneOffset() 方法返回当前语言环境下与 UTC 的时区偏移量(以分钟为单位)。
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

4
你没有理解问题。 - srsajid
4
您的代码示例与原问题无关。如何使用该库返回用户当前时区的名称? - Joe White

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接