【JS】公共组件整理包(不定期更新)

  1. 年月日时间格式化
  2. 时分秒格式化
  3. 时间戳转为多久之前
  4. 获取静态git图片
  5. 阿拉伯数字转换为中文
  6. rem引入
  7. 通过身份证获取年龄
  8. 通过身份证获取生日
  9. 通过身份证获取性别
    10.获取指定时间

年月日时间格式化

/*
 * @param date 标准时间格式:Fri Nov 17 2017 09:26:23 GMT+0800 (中国标准时间)
 * @param type 类型
 * type == 1 ---> "yyyy-mm-dd"
 * type == 2 ---> "yyyy年mm月dd日"
 * type == 3 ---> "yyyymmddhhMMss"
 * type == 4-- - > "yyyy-mm-dd-hh-MM-ss"
 * type == 5 ---> "yyyy-01-01" 返回当前年的1月1日
 * type == '' ---> "yyyy-mm-dd hh:MM:ss"
 */
export function formatDate(date, type){
  // 时间为空时候不需要进行操作
  if (!date) {
    return false
  }
  date = new Date(date)
  let year = date.getFullYear() // 年
  let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1 // 月
  let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate() // 日
  let hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours() // 时
  let minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes() // 分
  let seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds() // 秒
  if (type === 1) {
    return year + '-' + month + '-' + day
  } else if (type === 2) {
    return year + '年' + month + '月' + day + '日' + hour + '时' + minutes + '分'
  } else if (type === 3) {
    return year + '' + month + '' + day + '' + hour + '' + minutes + '' + seconds
  } else if (type === 4) {
    return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes
  } else if (type === 5) {
    return year + '-' + '01-01'
  } else {
    return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds
  }
}

时分秒格式化

// 将整数转换成 时:分:秒的格式
export const realFormatSecond = (second) => {
  var secondType = typeof second
  if (secondType === "number" || secondType === "string") {
    second = parseInt(second)
    var hours = Math.floor(second / 3600)
    second = second - hours * 3600
    var mimute = Math.floor(second / 60)
    second = second - mimute * 60
    // hours + ':' +
    return ("0" + mimute).slice(-2) + ":" + ("0" + second).slice(-2)
  } else {
    return "0:00:00"
  }
}

时间戳转为多久之前

export function timeFrom (timestamp = null, format = 'yyyy-mm-dd') {
  if (timestamp == null) timestamp = Number(new Date())
  timestamp = parseInt(timestamp)
  // 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
  if (timestamp.toString().length === 10) timestamp *= 1000
  var timer = (new Date()).getTime() - timestamp
  timer = parseInt(timer / 1000)
  // 如果小于5分钟,则返回"刚刚",其他以此类推
  let tips = ''
  switch (true) {
    case timer < 300:
      tips = '刚刚'
      break
    case timer >= 300 && timer < 3600:
      tips = parseInt(timer / 60) + '分钟前'
      break
    case timer >= 3600 && timer < 86400:
      tips = parseInt(timer / 3600) + '小时前'
      break
    case timer >= 86400 && timer < 2592000:
      tips = parseInt(timer / 86400) + '天前'
      break
    default:
      // 如果format为false,则无论什么时间戳,都显示xx之前
      if (format === false) {
        if (timer >= 2592000 && timer < 365 * 86400) {
          tips = parseInt(timer / (86400 * 30)) + '个月前'
        } else {
          tips = parseInt(timer / (86400 * 365)) + '年前'
        }
      } else {
        tips = moment(timestamp, format)
      }
  }
  return tips
}

获取静态git图片

// 获取静态git图片
export const getGifData = function (url) {
  return new Promise((resolve, reject) => {
    let ajax = null
    // 判断ajax对浏览器支持情况
    if (window.XMLHttpRequest) {
      ajax = new XMLHttpRequest()
    } else if (window.ActiveXObject) {
      ajax = new window.ActiveXObject()
    } else {
      alert('您的浏览器不支持ajax')
    }
    if (ajax != null) {
      ajax.open('GET', url, true)
      ajax.responseType = "blob"
      ajax.onload = function () {
        if (this.readyState !== 4) { return }
        var reader = new FileReader()
        reader.onload = function () {
          resolve(this.result)
        }
        reader.readAsDataURL(this.response)
      }
      ajax.send()
    } else {
      reject(new Error('error'))
    }
  })
}

阿拉伯数字转换为中文

// 阿拉伯数字转换为中文
export const sectionToChinese = (section) => {
  var chnNumChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  // var chnUnitSection = ['', '万', '亿', '万亿', '亿亿']
  var chnUnitChar = ['', '十', '百', '千']
  var strIns = ''
  var chnStr = ''
  var unitPos = 0
  var zero = true
  while (section > 0) {
    var v = section % 10
    if (v === 0) {
      if (!zero) {
        zero = true
        chnStr = chnNumChar[v] + chnStr
      }
    } else {
      zero = false
      strIns = chnNumChar[v]
      strIns += chnUnitChar[unitPos]
      chnStr = strIns + chnStr
    }
    unitPos++
    section = Math.floor(section / 10)
  }
  if (chnStr.startsWith('一十')) {
    chnStr = chnStr.replace('一十', '十')
  }
  return chnStr
}

rem引入

  import '@/js/rem.js'
// rem
(function() {
  const orientation = window.matchMedia('(orientation: portrait)')
  let width = document.documentElement.getBoundingClientRect().width // 获取宽度
  function onMatchMeidaChange(orientation) {
    if (orientation.matches) {
      // 竖屏
      width = document.documentElement.getBoundingClientRect().width // 获取竖屏宽度
      setTimeout(() => {
        // 重新计算竖屏宽度rem
        autoRootFontSize(width)
      })
    } else {
      // 横屏
      width = document.documentElement.getBoundingClientRect().width // 获取横屏宽度
      setTimeout(() => {
        // 重新计算横屏宽度rem
        autoRootFontSize(width)
      })
    }
  }
  onMatchMeidaChange(orientation)
  orientation.addListener(onMatchMeidaChange)
  /* 计算rem */
  function autoRootFontSize(width) {
    const baseSize = 16
    const scale = document.documentElement.clientWidth / 750
    document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + 'px'
    // // (当前屏幕宽度,最小宽度为1200)/1920*16px
    // const setSize = Math.max(width, 1200) / 1920 * 16
    // // 字体默认最大值为16px
    // document.documentElement.style.fontSize = (setSize > 16 ? 16 : setSize) + 'px'
  }
  window.addEventListener('resize', autoRootFontSize)
  autoRootFontSize()
})()

通过身份证获取年龄

  /**
   * 通过身份证获取年龄
   */
  getAge: function(idCard) {
    var year1;
    idCard = trim(idCard.replace(/ /g, ''));

    if (idCard.length == 15) {
      year1 = Number('19' + idCard.substring(6, 8));
    } else if (idCard.length == 18) {
      year1 = Number(idCard.substring(6, 10));
    } else {
      return null;
    }

    var year2 = (new Date()).getFullYear();

    return (year2 - year1);
  },

通过身份证获取生日

  /**
   * 通过身份证获取生日
   */
  getBirth: function(idCard) {
    idCard = trim(idCard.replace(/ /g, ''));
    var year = '';
    var month = '';
    var day = '';
    if (idCard.length == 15) {
      year = idCard.substring(6, 8);
      month = idCard.substring(8, 10);
      day = idCard.substring(10, 12);
      return '19' + year + month + day;
    } else if (idCard.length == 18) {
      year = idCard.substring(6, 10);
      month = idCard.substring(10, 12);
      day = idCard.substring(12, 14);
      return year + month + day;
    } else {
      return null;
    }
  },

通过身份证获取性别

  /**
   * 通过身份证判断是男是女
   */
  getSex: function(idCard) {
    idCard = trim(idCard.replace(/ /g, '')); // 对身份证号码做处理。包括字符间有空格。
    if (idCard.length == 15) {
      if (idCard.substring(14, 15) % 2 == 0) {
        return 2;
      } else {
        return 1;
      }
    } else if (idCard.length == 18) {
      if (idCard.substring(14, 17) % 2 == 0) {
        return 2;
      } else {
        return 1;
      }
    } else {
      return null;
    }
  },

获取指定时间

  // 获取指定时间,type:after 当天以后,before 当天以前;num: 间隔天数
  getAppointDate (type, num) {
    const date = new Date()
    let base = new Date(date).getTime()
    const oneDay = 24 * 3600 * 1000
    let dateArr = []
    const time = new Date(base)
    let month = time.getMonth() + 1
    if (month < 10) month = '0' + month
    dateArr.push([time.getFullYear(), month, time.getDate()].join('-'))
    for (let i = 1; i < num; i++) { // 控制需要的天数
      let now
      if (type === 'before') {
        now = new Date(base -= oneDay) // 这里控制往前一周还是往后一周
      } else if (type === 'after') {
        now = new Date(base += oneDay) // 这里控制往前一周还是往后一周
      }
      let _month = now.getMonth() + 1
      if (_month < 10) _month = '0' + _month
      dateArr.push([now.getFullYear(), _month, now.getDate()].join('-'))
    }
    return dateArr// 需要哪天直接下标取就行了
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值