【JavaScript】JS地下城-4F-時區

【JavaScript】JS地下城-4F-時區

4F-時區Link to this section

wp-image-256

連結Link to this section

Demo

Code

使用語言Link to this section

HTML、CSS、JavaScript(ES6)

BOSS 弱點Link to this section

  1. 【特定技術】僅能使用原生 JS 開發,不能使用套件
  2. 【特定技術】特別注意必須用 JS 處理各國時區
  3. 【書寫能力】請寫一篇 BLOG 來介紹你的挑戰過程,並介紹 JavaScript 如何提供 GMT、UTC 時區語法,以及何謂 TimeStamp。

技巧Link to this section

GMT、UTC 與 TimeStampLink to this section

  • GMT(格林威治標準時間):以英國格林威治天文台為基準的舊時間標準。
  • UTC(世界協調時間):目前國際通用的時間標準,與 GMT 幾乎相同(誤差在 1 秒内),現代系統一律使用 UTC。
  • Timestamp(時間戳):從 1970-01-01 00:00:00 UTC 開始累計的毫秒數(JavaScript)或秒數(其他語言),與時區無關。可以用 Date.now() 取得,也可以用 new Date(timestamp) 轉回時間物件。

要在 JavaScript 處理各國時區,最簡單的方式是 toLocaleString() 加上 timeZone option。

toLocaleString() 函式用法Link to this section

js
const time = new Date()

// 第一個參數:顯示語言&格式
// 第二個參數:option
console.log(time.toLocaleString('en-GB', {
  timeZone: 'UTC',
  hour12: false,
}))

這次使用到的 Option 有兩個:

  • timeZone
  • hour12
    • true //12小時制
    • false //24小時制

參考資料Link to this section

Date.prototype.toLocaleString() - JavaScript | MDN

Tags: