获取可分析的时区

Get Parseable Timezone

本文关键字:时区 可分析 获取      更新时间:2023-09-26
我正在使用Momentjs

和Momentjs Timezone来处理日期/时区。

我正在尝试让一个日期由特定时区的用户输入,并将其转换为他们自己时区的本地时间。 看起来 Moment 的时区库不支持用于设置时区的new Date().getTimezoneOffset()格式。

function calculateLocalTime(e) {
  var currentTz = new Date().getTimezoneOffset(),
      fromDate = moment.tz(this.value, 'GMT'),
      toDate = fromDate.tz(currentTz);
  $('to-time').val(toDate.format(dateFormat));
}

我也尝试从正常的Date对象中提取三个字母的时区,但这似乎也不被支持。

function calculateLocalTime(e) {
  var currentTz = new Date().toString().split(' ').pop().replace(/'(/gi, '').replace(/')/gi, ''),
      fromDate = moment.tz(this.value, 'GMT'),
      toDate = fromDate.tz(currentTz);
  $('to-time').val(toDate.format(dateFormat));
}

关于我应该如何使用 Moment 执行此操作的任何想法?

时刻时区用于处理来自 IANA TZ 数据库的标准标识符,例如 America/Los_Angeles

时刻.js 支持固定偏移区,独立于时刻时区,使用 zone 函数。

var m = moment();
// All of the following are equivalent
m.zone(480);        // minutes east of UTC, just like Date.getTimezoneOffset()
m.zone(8);          // hours east of UTC
m.zone("-08:00");   // hh:mm west of UTC  (ISO 8601)

但是,由于您说要转换为用户的本地时区,因此无需显式操作它。 只需使用local功能即可。

下面是一个完整的示例,从明确的 IANA 时区转换为用户的本地时区:

// Start at noon, Christmas Day, on Christmas Island (in the Indian Ocean)
var m = moment.tz('2014-12-25 12:00:00', 'Indian/Christmas');
// Convert to whatever the user's local time zone may be
m.local();
// Format it as a localized string for display
var s = m.format('llll');

对我来说,在美国太平洋时区运行这个,我得到"Wed, Dec 24, 2014 9:00 PM". 结果将根据代码的运行位置而有所不同。