[英]Get timezone name/list using timezone offset
我使用以下代碼進行時區偏移。 我想找出與時區偏移關聯的時區名稱列表。
新日期().getTimezoneOffset().toString()
我認為您必須為此使用moment-timezone.js
庫。
(鏈接在這里: https : //momentjs.com/timezone/ )
該方法應遵循以下原則:
moment.tz.names()
函數獲取所有可用的時區位置。 moment.tz.zone(name)
函數獲取區域對象 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>
您可以使用intl
object、本地“ia”(參見https://stackoverflow.com/a/64262840/1061871 )和Intl.supportedValuesOf('timeZone')
( https://developer. mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Intl/supportedValuesOf ):
const getOffset = (tz) => Intl.DateTimeFormat("ia", {
timeZoneName: "shortOffset",
timeZone: tz
})
.formatToParts()
.find((i) => i.type === "timeZoneName").value // => "GMT+/-OFFSET in hh:mm"
.slice(3); //remove the GMT to get the offset in hh:mm
const getTZList = (offset) =>
Intl.supportedValuesOf('timeZone').filter(tz => getOffset(tz) === offset)
console.log(getTZList("-3:30"), getTZList("")) //for list of timezone in gmt/utc use empty string, not 0
編輯,忘記了:日期 object 以 +/-hh:mm 格式偏移
const getUtcOffset = (dateObject = new Date()) => {
const offset = dateObject.getTimezoneOffset(), o = Math.abs(offset);
return (offset === 0 ? '' : ((offset < 0 ? "+" : "-") + ("00" + Math.floor(o / 60)).slice(-2) + ":" + ("00" + (o % 60)).slice(-2)));
}
console.log(getTZList(getUtcOffset(new Date()))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.