关于javascript:使用moment(timezone).js从用户浏览器获取时区

Get timezone from users browser using moment(timezone).js

使用moment.js和moment-timezone.js时,获取客户端时区并将其转换为其他时区的最佳方法是什么?

我想找出客户的时区,然后将其日期和时间转换为其他时区。

有人对此有经验吗?


当使用moment.js时,请使用:

1
var tz = moment.tz.guess();

它将返回IANA时区标识符,例如美国太平洋时区的America/Los_Angeles

它记录在这里。

在内部,它首先尝试使用以下调用从浏览器获取时区:

1
Intl.DateTimeFormat().resolvedOptions().timeZone

如果您只针对支持该功能的现代浏览器,而您不需要Moment-Timezone,则可以直接调用它。

如果Moment-Timezone无法从该函数中获得有效结果,或者该函数不存在,则它将通过针对Date对象测试几个不同的日期和时间来"猜测"时区,以查看其情况行为方式。猜测通常是一个足够好的近似值,但不能保证与计算机的时区设置完全匹配。


var timedifference = new Date()。getTimezoneOffset();

这将返回客户时区与UTC时间的时差。
然后,您可以根据需要使用它。


当使用moment.js时,moment(date).utcOffset()返回以参数传递的日期(或今天,如果没有传递的日期)的浏览器时间与UTC之间的分钟差(以分钟为单位)。
请勿在变量中设置此差异并将其用于选择的日期:

1
2
// this is WRONG! don't do it like this!
const OFFSET_UTC = moment().utcOffset();

上面的方法将当前差异应用于您使用的所有日期,如果您位于夏时制,则日期将在一年的另一半偏离一小时。

这是一个在选择的日期解析正确的偏移量的函数:

1
2
3
4
5
6
7
function getUtcOffset(date) {
  return moment(date)
    .add(
      moment(date).utcOffset(),
      'minutes')
    .utc()
}


您还可以使用以下JS代码获得所需的时间:

1
new Date(`${post.data.created_at} GMT+0200`)

在此示例中,我收到的日期为GMT + 0200时区。而不是每个时区。返回的数据将是您所在时区的日期。希望这可以帮助任何人节省时间


使用Moment库,请访问其网站-> https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/

我注意到他们也在他们的网站上使用了自己的库,因此您可以在安装前尝试使用浏览器控制台

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
moment().tz(String);

The moment#tz mutator will change the time zone and update the offset.

moment("2013-11-18").tz("America/Toronto").format('Z'); // -05:00
moment("2013-11-18").tz("Europe/Berlin").format('Z');   // +01:00

This information is used consistently in other operations, like calculating the start of the day.

var m = moment.tz("2013-11-18 11:55","America/Toronto");
m.format();                     // 2013-11-18T11:55:00-05:00
m.startOf("day").format();      // 2013-11-18T00:00:00-05:00
m.tz("Europe/Berlin").format(); // 2013-11-18T06:00:00+01:00
m.startOf("day").format();      // 2013-11-18T00:00:00+01:00

Without an argument, moment#tz returns:

    the time zone name assigned to the moment instance or
    undefined if a time zone has not been set.

var m = moment.tz("2013-11-18 11:55","America/Toronto");
m.tz();  // America/Toronto
var m = moment.tz("2013-11-18 11:55");
m.tz() === undefined;  // true