使用时刻(时区).js从用户浏览器获取时区

问题描述 投票:39回答:5

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

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

有没有人有这方面的经验?

javascript momentjs angular-moment
5个回答
14
投票

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

这将返回客户端时区与UTC时间的差异。然后你可以随心所欲地玩它。


162
投票

使用moment.js时,请使用:

var tz = moment.tz.guess();

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

这是documented here

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

Intl.DateTimeFormat().resolvedOptions().timeZone

如果您只定位支持此功能的现代浏览器,并且您不需要Moment-Timezone,那么您可以直接调用它。

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


5
投票

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

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

以上内容将对您使用的所有日期应用当前差异,如果您在夏令时区,如果它们在一年中的另一半,则日期将减去一小时。

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

function getUtcOffset(date) {
  return moment(date)
    .add(
      moment(date).utcOffset(), 
      'minutes')
    .utc()
}

1
投票

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

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

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


0
投票

使用Moment库,查看他们的网站 - > https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/

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

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
© www.soinside.com 2019 - 2024. All rights reserved.