JavaScript Date UTC & GMT All In One

发布时间 2023-09-06 13:46:36作者: xgqfrms

JavaScript Date UTC & GMT All In One

js 时期时区转换

使用场景

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

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()

(? 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

UTC

image

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

refs

https://time.is/zh/UTC

https://day.js.org/docs/en/plugin/timezone



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 ?️,侵权必究⚠️!