簡體   English   中英

使用時區偏移獲取時區名稱/列表

[英]Get timezone name/list using timezone offset

我使用以下代碼進行時區偏移。 我想找出與時區偏移關聯的時區名稱列表。

新日期().getTimezoneOffset().toString()

我認為您必須為此使用moment-timezone.js庫。

(鏈接在這里: https : //momentjs.com/timezone/

該方法應遵循以下原則:

  1. 導入庫(注意:該庫依賴moment.js庫-之前導入)
  2. 使用moment.tz.names()函數獲取所有可用的時區位置。
  3. 使用moment.tz.zone(name)函數獲取區域對象
  4. 使用區域對象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> 

您可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM