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>
yyyy/MM/dd hh:mm:ss、yyyy-MM-dd 等常用模板。使用 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'));