JavaScript关于格林威治时间与北京时间转换的问题

JavaScript关于格林威治时间与北京时间转换的问题

每次用每次要查,写个博客做个记录

首先是格林威治格式的时间字符串与北京时间的转换

function timeChange(time) {
    
    
  var date = time.substr(0, 10); //年月日
  var hours = time.substring(11, 13);
  var minutes = time.substring(14, 16);
  var seconds = time.substring(17, 19);
  var timeFlag = date + " " + hours + ":" + minutes + ":" + seconds;
  timeFlag = timeFlag.replace(/-/g, "/");
  timeFlag = new Date(timeFlag);
  timeFlag = new Date(timeFlag.getTime() + 8 * 3600 * 1000);
  timeFlag =
    timeFlag.getFullYear() +
    "-" +
    (timeFlag.getMonth() + 1 < 10
      ? "0" + (timeFlag.getMonth() + 1)
      : timeFlag.getMonth() + 1) +
    "-" +
    (timeFlag.getDate() < 10 ? "0" + timeFlag.getDate() : timeFlag.getDate()) +
    " " +
    timeFlag.getHours() +
    ":" +
    timeFlag.getMinutes() +
    ":" +
    (timeFlag.getSeconds() < 10
      ? "0" + timeFlag.getSeconds()
      : timeFlag.getSeconds());
  return timeFlag;
}

// 测试
const thistime = timeChange("2021-12-31T16:00:00.000Z");
console.log(thistime);
// 打印结果:2022-01-01 0:0:00

可以看出来,北京时间比格林威治时间晚8个小时

但有个问题,这个函数中的时间格式是字符串格式,有些情况下,从数据库中取出都时间就是格林威治时间对象,并非字符串,要使用上面代码的话,需要把时间转换一下**(按照逻辑,应该可以直接将格林威治时间转为北京时间,不用绕这么多圈)**,之前以为可以直接用toString()转换,发现根本不行,问了下ChatGPT,它给了个解决方案,如下

function formatGMTDateToString(gmtDate) {
    
    
    const year = gmtDate.getUTCFullYear();
    const month = gmtDate.getUTCMonth() + 1;
    const day = gmtDate.getUTCDate();
    const hours = gmtDate.getUTCHours();
    const minutes = gmtDate.getUTCMinutes();
    const seconds = gmtDate.getUTCSeconds();
    
    const dateString = `${
      
      year}-${
      
      formatNumber(month)}-${
      
      formatNumber(day)} ${
      
      formatNumber(hours)}:${
      
      formatNumber(minutes)}:${
      
      formatNumber(seconds)}`;
    return dateString;
  }
  
  function formatNumber(number) {
    
    
    return number < 10 ? `0${
      
      number}` : number;
  }

// 测试
  const gmtDate = new Date(); // 创建一个表示当前时间的格林威治时间对象
  console.log(gmtDate)  // 2023-06-29T05:48:51.688Z 这并不是个字符串,而是个时间格式的数据
  const dateString = formatGMTDateToString(gmtDate)  
  console.log(dateString)  // 2023-06-29 05:48:51  这是字符串格式的格林威治时间

接着就可以调用上面的timeChange方法将字符串格式的格林威治时间转换成北京时间了,也是字符串格式

猜你喜欢

转载自blog.csdn.net/u012848304/article/details/131454932