根据 时区 计算出 指定时间 在 该时区的 时间 ,parseInt的奇特用法

 

/**
 * 
 * @param {*} time 时间戳 或者 YYYY/MM/DD hh:mm:ss格式的时间
 * @param {*} timezone 客服设置的时区,可以是: "GMT+8" 或 8 
 * @param {*} cFormat 返回的时间格式
 * @return 在当地显示客服设置的时区的时间
 */
export function getCustomTimezoneTime(time, timezone, cFormat = '') {
  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)
}

 

// 格式化时间
export 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()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return value
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

 

答疑:

'{y}-{m}-{d} {h}:{i}:{s}'.replace(/{(y|m|d|h|i|s|a)+}/g,(result,key) => {
            console.log("result: " + result + " key:" + key);
        })

 

parseInt的奇特用法
        console.log(parseInt(["+1"],10));//   1
        console.log(parseInt(["-1"],10));//   -1
        console.log(parseInt(["+0"],10));//   0
        console.log(parseInt(["-0"],10));//   -0
        console.log(parseInt("+0",10));//   0
        console.log(parseInt("-0",10));//   -0
        console.log(parseInt("+8",10));//   8
        console.log(parseInt("-8",10));//   -8
        console.log(parseInt(0-0,10));//   0

我好奇的是  他能接收 数组!!! 且数组的第一位才生效

 

 

 

posted @ 2020-07-15 14:18  古墩古墩  Views(444)  Comments(0Edit  收藏  举报