2024年4月15日 星期一

在 Intl.DateTimeFormat 顯示時區

 在 Intl.DateTimeFormat 顯示時區

前言

  先前使用 Intl.DateTimeFormat 都沒顯示時區,要如何顯示呢?在此把學習的過程做個紀錄。


內容

  範例如下

const date = new Date(Date.UTC(2020, 11, 20, 16, 23, 16, 738));
//
console.log(new Intl.DateTimeFormat('zh-tw',{
  hourCycle : 'h23',
  timeZoneName : 'short',
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second : 'numeric',
  fractionalSecondDigits: 3,
  
}).format(date));//2020年12月21日 星期一 00:23:16.738 [GMT+8]
//
console.log(new Intl.DateTimeFormat('zh-tw',{
  hourCycle : 'h23',
  timeZoneName : 'long',
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second : 'numeric',
  fractionalSecondDigits: 3,
  
}).format(date));//2020年12月21日 星期一 00:23:16.738 [台北標準時間]
//
console.log(new Intl.DateTimeFormat('zh-tw',{
  hourCycle : 'h23',
  timeZoneName : 'shortOffset',
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second : 'numeric',
  fractionalSecondDigits: 3,
  
}).format(date));//2020年12月21日 星期一 00:23:16.738 [GMT+8]
//
console.log(new Intl.DateTimeFormat('zh-tw',{
  hourCycle : 'h23',
  timeZoneName : 'longOffset',
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second : 'numeric',
  fractionalSecondDigits: 3,
  
}).format(date));//2020年12月21日 星期一 00:23:16.738 [GMT+08:00]
//
console.log(new Intl.DateTimeFormat('zh-tw',{
  hourCycle : 'h23',
  timeZoneName : 'shortGeneric',
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second : 'numeric',
  fractionalSecondDigits: 3,
  
}).format(date));//2020年12月21日 星期一 00:23:16.738 [台灣時間]
//
console.log(new Intl.DateTimeFormat('zh-tw',{
  hourCycle : 'h23',
  timeZoneName : 'longGeneric',
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second : 'numeric',
  fractionalSecondDigits: 3,
  
}).format(date));//2020年12月21日 星期一 00:23:16.738 [台北標準時間]


透過 timeZoneName 可以顯示時區,但只能用於自訂格式,如果與 dateStyle 或 timeStyle 混用會報錯,有六種參數可以用, short 、 long 、shortOffset 、 longOffset 、 shortGeneric 與 longGeneric ,範例分別個示範一次。


參考資料

[ developer.mozilla.org ] Intl.DateTimeFormat() constructor'


相關文章與資料

初探 Intl.DateTimeFormat

調整 Intl.DateTimeFormat 的格式

自訂 Intl.DateTimeFormat 的格式

調整 Intl.DateTimeFormat 的時間為 24 小時制

沒有留言:

張貼留言