【问题标题】:Get Parseable Timezone获取可解析的时区
【发布时间】:2014-12-26 17:39:44
【问题描述】:

我正在使用MomentjsMomentjs 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 执行此操作有任何想法吗?

【问题讨论】:

    标签: javascript date timezone momentjs


    【解决方案1】:

    Moment-timezone 用于使用来自IANA TZ Database 的标准标识符,例如America/Los_Angeles

    Moment.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"。结果会因代码运行的位置而异。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多