util.js 2.4 KB
let util = {}
util.dateFormat = function(dateTime, format = 'YYYY-MM-DD') {
  const date = new Date(dateTime)
  const config = {
    YYYY: date.getFullYear(),
    MM: appendZero(date.getMonth() + 1), //getMonth() 方法根据本地时间返回指定日期的月份(从 0 到 11)
    DD: appendZero(date.getDate()),
    HH: appendZero(date.getHours()),
    mm: appendZero(date.getMinutes()),
    ss: appendZero(date.getSeconds())
  }
  for (const key in config) {
    format = format.replace(key, config[key])
  }
  return format
}

function appendZero(int) {
  if (int < 10) {
    return '0' + `${int}`
  } else {
    return int
  }
}
util.decimal = function(num, fixed) {
  let pow = Math.pow(10, fixed)
  return Math.round(num * pow) / pow
}
util.getLastDay = function(date) {
  let current = new Date(date)
  let currentMonth = current.getMonth()
  let nextMoth = ++currentMonth
  let nextMonthDayOne = new Date(current.getFullYear(), nextMoth, 1)
  let minusDate = 1000 * 60 * 60 * 24
  return new Date(nextMonthDayOne.getTime() - minusDate)
}
util.getDateStr = function(num) {
  let now = new Date()
  now.setDate(now.getDate() + num)
  util.dateFormat(now)
    // let y = now.getFullYear()
    // let m = (now.getMonth() + 1) < 10 ? '0' + (now.getMonth() + 1) : (now.getMonth() + 1)
    // let d = now.getDate() < 10 ? '0' + now.getDate() : now.getDate()

  // return y + "-" + m + "-" + d
  return util.dateFormat(now)
}
util.getExplorer = function() {
  var ua = navigator.userAgent.toLocaleLowerCase();
  var browserType = null;
  if (ua.match(/msie/) != null || ua.match(/trident/) != null) {
    browserType = "IE";
  } else if (ua.match(/firefox/) != null) {
    browserType = "火狐";
  } else if (ua.match(/ubrowser/) != null) {
    browserType = "UC";
  } else if (ua.match(/opera/) != null) {
    browserType = "欧朋";
  } else if (ua.match(/bidubrowser/) != null) {
    browserType = "百度";
  } else if (ua.match(/metasr/) != null) {
    browserType = "搜狗";
  } else if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null) {
    browserType = "QQ";
  } else if (ua.match(/maxthon/) != null) {
    browserType = "遨游";
  } else {
    browserType = '谷歌'
  }
  return browserType
}
util.debounce=(fn,timer)=> {
  let timeout = null;
  return function () {
      clearTimeout(timeout); 
      timeout = setTimeout(() => {
          fn.apply(this, arguments);
      }, timer);
  };
}
export default util