我有以下价值 -
GMT -0800
如何获得共享此偏移量的所有时区列表?
答案 0 :(得分:1)
我将分两部分回答:
1)查找包含时区名称的数据集&他们的抵消
您可以手动编译此数据集(可能使用来自维基百科的数据),或者NPM包timezones.json似乎看起来合适。
2)搜索列表
给出两个输入:初始时区&您需要的偏移量(例如GMT
& -8
):
在数据集中搜索初始时区的偏移量(例如GMT
为+0
)
将两个值加在一起,例如GMT-8
=> 0 - 8 = -8
过滤数据集,使其偏移量为-8
示例:强>
假设您在变量timezones.json
timezones_file
的内容
const timezones = JSON.parse(timezones_file);
// Step 1 above
function findOffset(timezone) {
const matches = timezones.filter( zone => zone.abbr === timezone );
return matches ? matches[0].offset : null;
}
// Step 2 above
function findByOffset(offset) {
return timezones.filter( zone => zone.offset === offset );
}
// Answer to your question, accepts a timezone (e.g. 'GMT') and offset (e.g. -8)
function getListOfTimezones(initial_timezone, initial_offset) {
const new_offset = findOffset(initial_timezone) + initial_offset;
return findByOffset(new_offset);
}
答案 1 :(得分:1)
以下是按偏移列出时区的示例,值得指出的是,由于许多区域的夏令时,给定时区的UTC偏移会发生变化。
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.slim.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-2012-2022.js"></script>
<script>
function initialise() {
$("#offsetSelector").on('change', function (event) {
showTimeZones();
});
var startOffset = -12;
var offsets = Array.from(Array(48).keys()).reduce((acc, val) => {
acc.push(startOffset);
startOffset += 0.5;
return acc;
}, []);
offsets.forEach((offset) => {
var selector = document.getElementById("offsetSelector");
var el = document.createElement("option");
el.textContent = offset;
el.value = offset;
selector.appendChild(el);
});
document.getElementById("offsetSelector").value = -8;
showTimeZones();
}
function showTimeZones() {
var utcOffset = $('#offsetSelector').val();
var timeZones = moment.tz.names();
var result = timeZones.filter((zone) => {
var tz = moment.tz.zone(zone);
/* We'll make the assumption we're looking for the offset outside of DST */
var currentOffset = tz.utcOffset(new Date('2018-01-01'));
return (currentOffset === (-utcOffset*60));
});
$("#list").empty();
console.log('Zones:');
result.forEach((zoneName) => {
console.log(zoneName);
var ul = document.getElementById("list");
var li = document.createElement("li");
li.innerHTML = zoneName;
// li.appendChild(document.createTextNode(zoneName));
ul.appendChild(li);
});
}
</script>
</head>
<body onLoad = "initialise()">
<b>Offset (hours):</b>
<select id="offsetSelector">
</select>
<br/><br/><b>TimeZone list:</b><br/>
<ul id="list"></ul>
</body>
</html>
的jsfiddle: https://jsfiddle.net/p9h5wgcr/