2024年3月4日 星期一

初探 Intl.DateTimeFormat

 初探 Intl.DateTimeFormat

前言

  如果時間格式需要在地化時要如何做呢? JavaScript 本身提供在地化的方法,也就是 Intl.DateTimeFormat() ,在此把學習的過程做個紀錄。


內容

  範例如下

const date = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));
console.log(new Intl.DateTimeFormat('en-US').format(date));//12/20/2020
console.log(new Intl.DateTimeFormat('zh-tw').format(date));//2020/12/20
console.log(new Intl.DateTimeFormat('fr').format(date));//20/12/2020


使用 Intl.DateTimeFormat() 的方式很簡單,用 new 方式來喚起!並輸入要在地化的區域碼,再對創建的物件喚起 format() 並輸入要在地化的時間,就可以得到在地化的結果,範例的美國時間順序是"月/日/年",台灣是"年/月/日",最後法國是 "日/月/年"。


參考資料

[ developer.mozilla.org ] Intl.DateTimeFormat

沒有留言:

張貼留言