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

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

在使用 moment.js 和 moment-timezone.js

时获取客户时区并将其转换为其他时区的最佳方法是什么

我想知道什么是客户时区,然后将他的日期和时间转换成其他时区。

有人有这方面的经验吗?

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

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

使用moment.js时,使用:

var tz = moment.tz.guess();

它将return一个IANA时区标识符,例如America/Los_Angeles代表美国太平洋时区。

documented here.

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

Intl.DateTimeFormat().resolvedOptions().timeZone

如果您只针对支持此功能的现代浏览器,并且您不需要 Moment-Timezone 来做任何其他事情,那么您可以直接调用它。

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

所有当前答案都提供当前时间的偏移差异,而不是给定日期。

moment(date).utcOffset() returns 浏览器时间与 UTC 在作为参数传递的日期之间的时差(以分钟为单位)(或今天,如果没有日期过去)。

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

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

您也可以使用以下JS代码获取您想要的时间:

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

在这个例子中,我收到的日期是 GMT+0200 时区。取而代之的是每个时区。返回的数据将是您所在时区的日期。希望这会帮助任何人节省时间

使用 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

如果用户的时区是您想要的,那么

const localtz = moment.tz.guess() // returns user's timezone

此外,如果您想使用它,那么将时间戳转换为用户时区的最佳方法是

const time = moment.tz(response.timestamp)
const localtz = moment.tz.guess() // user's timezone
const date = time.clone().tz(localtz) // convert time to user's timezone

这里localtz是用户的时区,使用它我们可以将时间戳转换为用户的本地时间

首先,您可以使用以下方法找出客户的时区

let zoneVal = moment().tz(Intl.DateTimeFormat().resolvedOptions().timeZone).format('Z')

它会 return 你 GMT 时区格式例如 +5:30 (colombo/srilanka & Delhi/India) 或 +6:00(孟加拉国达卡) 取决于你所在的地区在.

其次, 如果您想找出特定时区的时间,请执行以下操作

moment.tz("Asia/Dhaka").format()

这将 return 达卡的 ISO 格式的时区值。