已知时间转换为指定时区的时间

 与后台交互,尽量传时间戳,时间戳都是0时区的,如果传2021这种格式的,不确定是哪个时区的!!!

/**
   * time:已知的时间戳或'{y}-{m}-{d} {h}:{i}:{s}'格式的时间
   * timezone:时区  8、-8、+8
   * cFormat:时间格式 'timestamp'或'{y}-{m}-{d} {h}:{i}:{s}' 中间符号随便变
  */
function getCustomTimezoneTime(time, timezone, cFormat = '') {//将时间戳或'{y}-{m}-{d} {h}:{i}:{s}'格式的时间转换为 指定时区的时间
    time = new Date(time).getTime()
  if (typeof time !== 'number' || isNaN(time)) return null
  timezone = timezone + ''
  let reg = /[+-]?d+/,
    zone = timezone.match(reg), //客服时区,如 -6
    customTime = parseInt(zone, 10) * 60 * 60 * 1000; // 客服时区时间差
  let localTimezone = new Date().getTimezoneOffset(),//协调世界时(UTC)相对于当前时区的时间差值  单位(分钟)  注意:本地时间+这个差值=世界时间
    localTime = localTimezone * 60 * 1000;//本体时间差
  customTime = time + localTime + customTime;//这相当于指定时间的世界时间
  return parseTime(customTime, cFormat)
}

function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  if (time === null || time === undefined) {
    return null
  }
  if (typeof new Date(time).getTime() !== 'number') {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  if(format === 'timestamp'){
    //可以返回 时间戳
    return date.getTime();
  }else{
    // 返回指定格式的 时间
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
      let value = formatObj[key]
      if (key === 'a') {
        return value
      }
      if (result.length > 0 && value < 10) {
        value = '0' + value
      }
      return value || 0
    })
    return time_str
  }
}

// let newDate ='2021-01-21 18:05:18';//一个指定的时间格式  可以传指定格式的时间
let newDate = new Date().getTime();//当前时间戳 0 时区的时间  传时间戳也行
console.log(newDate);
let formatDate = getCustomTimezoneTime(newDate,"8");//8时区
console.log(formatDate);
// console.log(parseTime(formatDate));
console.log(parseTime(formatDate,'timestamp'));

原文地址:https://www.cnblogs.com/fqh123/p/14309662.html