萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 即時顯示北京時間(含時區轉換與格式化)

核心原理

JavaScript Date 物件內部儲存 UTC 時間戳。瀏覽器根據用戶系統時區顯示本地時間。要顯示北京時間(UTC+8),需根據本地時區偏移進行計算。

完整實作

<span id="bjTime"></span>

<script>
// 日期格式化擴充
Date.prototype.format = function (fmt) {
  const o = {
    'M+': this.getMonth() + 1,
    'd+': this.getDate(),
    'h+': this.getHours(),
    'm+': this.getMinutes(),
    's+': this.getSeconds(),
    'q+': Math.floor((this.getMonth() + 3) / 3),
    'S': this.getMilliseconds()
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
    }
  }
  return fmt;
};

// UTC 轉北京時間(UTC+8)
function getBeijingTime(date = new Date()) {
  const localOffset = date.getTimezoneOffset(); // 分鐘,本地與 UTC 差值(如 UTC+8 為 -480)
  const beijingOffset = -8 * 60;                // 北京 UTC+8 → -480 分鐘
  const diff = beijingOffset - localOffset;     // 需調整的分鐘數
  return new Date(date.getTime() + diff * 60000);
}

// 每秒更新
setInterval(() => {
  const bj = getBeijingTime();
  document.getElementById('bjTime').textContent = bj.format('yyyy/MM/dd hh:mm:ss');
}, 1000);
</script>

關鍵點說明

  1. getTimezoneOffset():回傳「本地時間 - UTC」的分鐘數。東京/北京 (UTC+9/+8) 回傳負值(-540/-480)。
  2. 計算差值:目標時區偏移 - 當前偏移 = 需加減的分鐘數。
  3. 避免夏令時問題:中國大陸不實施夏令時,固定 UTC+8,上述計算恆準確。
  4. 格式化函式:支援 yyyy/MM/dd hh:mm:ss、yyyy-MM-dd 等常用模板。

進階:支援任意 IANA 時區

使用 Intl.DateTimeFormat(現代瀏覽器支援):

function formatInTimeZone(date, timeZone, fmt) {
  const opts = {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    hour12: false, timeZone
  };
  const parts = new Intl.DateTimeFormat('zh-CN', opts).formatToParts(date);
  const map = {};
  parts.forEach(p => map[p.type] = p.value);
  return fmt
    .replace('yyyy', map.year)
    .replace('MM', map.month)
    .replace('dd', map.day)
    .replace('hh', map.hour)
    .replace('mm', map.minute)
    .replace('ss', map.second);
}

// 使用
console.log(formatInTimeZone(new Date(), 'Asia/Shanghai', 'yyyy/MM/dd hh:mm:ss'));
console.log(formatInTimeZone(new Date(), 'America/New_York', 'yyyy/MM/dd hh:mm:ss'));

應用場景

  • 全球電商網站顯示統一「北京時間」下單截止倒數。
  • 跨國視訊會議顯示各參與城市當地時間。
  • 日誌系統統一記錄 UTC,前端按用戶偏好時區顯示。
copyright © 萬盛學電腦網 all rights reserved