【问题标题】:Get timezone name/list using timezone offset使用时区偏移量获取时区名称/列表
【发布时间】:2020-01-02 04:25:00
【问题描述】:

我正在使用以下代码进行时区偏移。 我想找出与时区偏移相关的时区名称列表。

new Date().getTimezoneOffset().toString()

【问题讨论】:

  • 这只能获得匹配 current 偏移量的时区 - 即基于 new Date() 返回的“现在”的时区。请参阅timezone 标签 wiki 中的“时区!= 偏移量”。
  • 您最好使用Intl.DateTimeFormat().resolvedOptions().timeZone 来收集客户的时区ID。

标签: javascript timezone momentjs timezone-offset


【解决方案1】:

我认为您必须为此使用moment-timezone.js 库。

(此处链接:https://momentjs.com/timezone/

方法应该遵循以下原则:

  1. 导入库(注意:此库依赖于moment.js 库 - 之前导入)
  2. 使用moment.tz.names() 函数获取所有可用的时区位置。
  3. 使用moment.tz.zone(name)函数获取zone object
  4. 使用 zone 对象中的offsets 属性 获取位置偏移量
  5. 创建一个地图来保存相同的偏移名称。
  6. 遍历偏移量(一个位置可以共享多个偏移量)并将它们添加到地图以及每个键的位置名称。
  7. 访问具有特定偏移量的地图并获取时区列表。

代码如下所示:

const tzNames = moment.tz.names();
const map = new Map();

for (const name of tzNames) {
  const offsets = moment.tz.zone(name).offsets;
  
  for (const offset of offsets) {
      if (!map.has(offset)) {
          map.set(offset, new Set());
      }

      map.get(offset).add(name);
  }
}

const currentOffset = new Date().getTimezoneOffset();
const offsetList = map.get(currentOffset);

console.log('currentOffset: ' + currentOffset);
console.log('offset list size: ' + offsetList.size);
console.log('Total different offsets: ' + map.size);

console.log('List items: ');
for (const item of offsetList) {
  console.log(item);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>

【讨论】:

    猜你喜欢
    • 2014-02-15
    • 2011-02-28
    • 2016-05-07
    • 2021-04-11
    • 1970-01-01
    • 2020-12-28
    • 2020-04-20
    • 1970-01-01
    • 2016-08-06
    相关资源
    最近更新 更多