使用时区偏移获取时区 name/list
Get timezone name/list using timezone offset
我正在使用以下代码设置时区偏移量。
我想找出与时区偏移关联的时区名称列表。
new Date().getTimezoneOffset().toString()
我认为您必须为此使用 moment-timezone.js
库。
(Link 这里: https://momentjs.com/timezone/)
方法应该沿着这条线:
- 导入库(注意:此库依赖于 moment.js 库 - 导入之前的库)
- 使用
moment.tz.names()
函数获取所有可用的时区位置。
- 使用
moment.tz.zone(name)
函数得到zone object
- 使用 区域对象 中的
offsets
属性 获取位置偏移量
- 创建一个地图来保存相同的偏移量名称。
- 遍历偏移量(一个位置可以共享多个偏移量)并将它们添加到地图以及每个键的位置名称。
- 访问具有特定偏移量的地图并获取时区列表。
代码看起来像这样:
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>
我正在使用以下代码设置时区偏移量。 我想找出与时区偏移关联的时区名称列表。
new Date().getTimezoneOffset().toString()
我认为您必须为此使用 moment-timezone.js
库。
(Link 这里: https://momentjs.com/timezone/)
方法应该沿着这条线:
- 导入库(注意:此库依赖于 moment.js 库 - 导入之前的库)
- 使用
moment.tz.names()
函数获取所有可用的时区位置。 - 使用
moment.tz.zone(name)
函数得到zone object - 使用 区域对象 中的
offsets
属性 获取位置偏移量 - 创建一个地图来保存相同的偏移量名称。
- 遍历偏移量(一个位置可以共享多个偏移量)并将它们添加到地图以及每个键的位置名称。
- 访问具有特定偏移量的地图并获取时区列表。
代码看起来像这样:
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>