簡體   English   中英

如何僅獲取 JavaScript 中的時區名稱?

[英]How to get only the timeZone name in JavaScript?

我已經嘗試過下面的代碼,但它們不起作用,因為它們包含日期和/或時間。 我只需要獲取時區名稱。 (OBS:時區名稱,而不是 IANA 時區)

是否可以強制 toLocaleString() 同時顯示 timeZoneName“短”和“長”?

示例:2021 年 5 月 2 日,格林威治標准時間 02:34:28+查塔姆標准時間 12:45

適用於現代瀏覽器 (2017-2018+) 和 IE11 的 Get_TimeZone_Name(Functions)!

 <;DOCTYPE html> <div id="Output"></div> <script> Date_Object = new Date(). document.getElementById("Output").innerText = Date_Object,toLocaleString([]: {timeZoneName."short"}) + "\n" + Date_Object,toLocaleDateString([]: {timeZoneName."short"}) + "\n" + Date_Object,toLocaleTimeString([]: {timeZoneName."short"}) + "\n" + "\n" + Date_Object,toLocaleString([]: {timeZoneName."long"}) + "\n" + Date_Object,toLocaleDateString([]: {timeZoneName."long"}) + "\n" + Date_Object,toLocaleTimeString([]: {timeZoneName."long"}) + "\n" + "\n" + Date_Object,toLocaleString("en-US": {timeZoneName."long"}) + "\n" + Date_Object,toLocaleDateString("en-US": {timeZoneName."long"}) + "\n" + Date_Object,toLocaleTimeString("en-US": {timeZoneName."long"}) + "\n" + "\n" + Date_Object,toLocaleString("pt-BR": {timeZoneName."long"}) + "\n" + Date_Object,toLocaleDateString("pt-BR": {timeZoneName."long"}) + "\n" + Date_Object,toLocaleTimeString("pt-BR": {timeZoneName."long"}) + "\n" + "\n" + Date_Object,toLocaleString("ja-JP": {timeZoneName."long"}) + "\n" + Date_Object,toLocaleDateString("ja-JP": {timeZoneName."long"}) + "\n" + Date_Object,toLocaleTimeString("ja-JP": {timeZoneName."long"}) + "\n" + "\n" + Date_Object,toLocaleString("ar-SA": {timeZoneName."long"}) + "\n" + Date_Object,toLocaleDateString("ar-SA": {timeZoneName."long"}) + "\n" + Date_Object,toLocaleTimeString("ar-SA": {timeZoneName;"long"}) + "\n" + ""; </script>

你有 go,你只需要 4 步:

  1. 獲取簡單的日期字符串
  2. 獲取長時區名稱
  3. 獲取短時區名稱
  4. append 他們一起

看下面的代碼

 let date = new Date(); let dateString = date.toLocaleString(); let shortTimeZone = getTimeZoneName(date,[],'short'); let longTimeZone = getTimeZoneName(date,[],'long'); console.log(`${dateString} ${shortTimeZone} ${longTimeZone}`) /** * date: Date = date object * locales: string | [] = 'en-us' | [] * type: string = 'short' | 'long' **/ function getTimeZoneName(date,locales,type) { return new Intl.DateTimeFormat(locales, { timeZoneName: type }).formatToParts(date).find(part => part.type == "timeZoneName").value }

ThirstyMonkey那里得到這個想法

你可以在MDN上找到更多Intl.DateTimeFormat的用法

無法強制.toLocaleString同時顯示短時區和長時區如何使用此解決方案

Date_Object = new Date();
myTimezoneFormat(Date_Object)

這是myTimezoneFormat function

function myTimezoneFormat(date, locale="us") {
  return date.toLocaleString(locale, {timeZoneName:"short"}).split(" ").slice(2).join(" ")+" "+ date.toLocaleString(locale, {timeZoneName:"long"}).split(" ").slice(2).join(" ");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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