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

nem*_*_87 53 javascript momentjs angular-moment

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

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

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

Mat*_*int 173

使用moment.js时,请使用:

var tz = moment.tz.guess();
Run Code Online (Sandbox Code Playgroud)

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

这是记录在这里.

  • +1.确保您使用日期时使用tz挂钩.https://momentjs.com/timezone/docs/用node.js安装它使用这个命令`npm install moment-timezone`然后需要它像`window.moment = require('moment-timezone');` (3认同)
  • 很好的答案 - 赞成!也请使用 `momet-timezone` 版本 **0.5.4** 或更高...请按照此线程进一步解释 https://github.com/moment/moment-timezone/issues/324 (2认同)
  • 时区是从浏览器还是设备中获取的? (2认同)
  • @bubble - 它取自代码正在执行的任何环境。 (2认同)

jog*_*goe 12

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

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

  • 这将返回*current*时区*offset*.不是时区.偏移可以根据夏令时等因素而改变.请参阅[时区标签维基]中的"时区!=偏移"(http://stackoverflow.com/tags/timezone/info) (33认同)
  • @MattJohnson的回答是这个问题的真实答案.从技术上讲,这个答案是错误的,因为它与偏移相关,而不是与时区相关(不同的概念). (6认同)

And*_*hiu 6

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

function getUtcOffset(date) {
  return moment(date)
    .subtract(
      moment(date).utcOffset(), 
      'minutes')
    .utc()
}
Run Code Online (Sandbox Code Playgroud)

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

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

function getUtcOffset(date) {
  return moment(date)
    .subtract(
      moment(date).utcOffset(), 
      'minutes')
    .utc()
}
Run Code Online (Sandbox Code Playgroud)

  • @Milkncookiez,我更新了答案.谢谢.不知道我是如何颠倒他们的(这可能是一种双向工作或在某些先前版本中被改变的情况 - 我发布我未测试的东西的概率接近于'null`). (2认同)

Phi*_*ppe 5

使用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
Run Code Online (Sandbox Code Playgroud)