JavaScript Date UTC & GMT All In One
js 时期
时区转换
UTC
& GMT
Coordinated Universal Time / 协调世界时
UTC 是最主要的世界时间标准
,其以原子
时的秒长为基础,在时刻上尽量接近
于格林威治标准时间。
UTC 实际上与 GMT 基本相同.
https://zh.wikipedia.org/zh-hans/协调世界时
Greenwich Mean Time / 格林威治标准时间 (英国)
https://zh.wikipedia.org/zh-hans/格林尼治標準時間
使用场景
GitHub Actions 定时任务时间戳不准确 bug
const date = new Date();
const month = `${date.getMonth()+ 1}`.padStart(2, `0`)
const day = `${date.getDate()}`.padStart(2, `0`)
const hour = `${date.getHours()}`.padStart(2, `0`)
const minute = `${date.getMinutes()}`.padStart(2, `0`)
this.date = date.toString();
// this.date = date.toUTCString();
// this.date = date.toGMTString();
// this.date = date.toISOString();
solution
timezone +8 / -8
tips: 左加右减 / 西减东加
new Date()
// Wed Sep 06 2023 03:14:43 GMT+0800 (China Standard Time)
new Date(`${new Date().toUTCString()}+0800`);
// Tue Sep 05 2023 19:14:47 GMT+0800 (China Standard Time)
new Date(`${new Date().toUTCString()}-0800`);
// Wed Sep 06 2023 11:15:16 GMT+0800 (China Standard Time)
const changeUTCTimeToChinaTime = () => {
const timestamp = Date.now();
// GMT+0800 (China Standard Time)
// 28800000 毫秒 = 60 分/时 * 8 时 * 60 秒/分 * 1000 毫秒/秒
return new Date(timestamp - 60 * 8 * 60 * 1000)
}
// UTC to China - 8
const convertUTCTimeToChinaTime = () => {
const date = new Date()
const cmtTime = date.toGMTString()
// GMT+0800 (China Standard Time)
// 480 分 = 60 分/时 * 8 时
// return new Date(utcTime - 480);
const str = new Date(`${cmtTime}-0800`).toGMTString();
const time = str.split(` `)[4];
// return new Date(`${cmtTime}-0800`);
// return new Date(`${date.toGMTString()}-0800`).toGMTString();
}
const china = convertUTCTimeToChinaTime();
demos
function changeTimezone(us) {
// suppose the date is 00:00 UTC
const china = new Date(us.toLocaleString('zh-CN', {timeZone: "Asia/Shanghai"}));
// const china = new Date(us.toLocaleString('en-US', { timeZone: 'America/New_York'}));
// it will be 08:00 in China and the diff is 8 hours
const diff = us.getTime() - china.getTime();
return new Date(us.getTime() - diff);
}
function getChinaTime() {
const us = new Date();
const china = changeTimezone(us);
console.log(`us: ${us.toString()}`);
console.log(`china: ${china.toString()}`);
}
// getChinaTime()