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

时间:2016-11-03 12:29:50

标签: javascript momentjs angular-moment

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

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

有人有这方面的经验吗?

6 个答案:

答案 0 :(得分:143)

使用moment.js时,请使用:

var tz = moment.tz.guess();

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

documented here

答案 1 :(得分:9)

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

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

答案 2 :(得分: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()
}

答案 3 :(得分:1)

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

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

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

答案 4 :(得分:0)

使用时刻库,请访问其网站-> 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

答案 5 :(得分:0)

获取用户时区的最佳方式是使用

const time = moment.tz(response.timestamp)
const localtz = moment.tz.guess()
const date = time.clone().tz(localtz)

这样您就可以将您的时间转换为本地时区特定时间