封装的时间组件vue

封装的时间组件vue
一、工具函数

/**
 * Created by PanJiaChen on 16/11/18.
 */
/** 计算某一月有多少天**/
export function getCountDays(year,mouth) {
          var curDate = new Date();
            curDate.setFullYear(year)
          /* 获取当前月份 */

         /*  生成实际的月份: 由于curMonth会比实际月份小1, 故需加1 */
         curDate.setMonth(mouth);
         /* 将日期设置为0, 这里为什么要这样设置, 我不知道原因, 这是从网上学来的 */
         curDate.setDate(0);
         /* 返回当月的天数 */
        return curDate.getDate();
 }

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat = '{y}-{m}-{d}') {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'undefined' || time === null || time === 'null') {
    return ''
  } else 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
}
export function timeSpents(a, b) {
  if (!a && !b) {
    return 0 + ' ' + '分钟'
  } else {
    var startTime = a
    var endTime = b
    var start1 = startTime.split(':')
    var startAll = parseInt(start1[0]) * 60 + parseInt(start1[1])
    var end1 = endTime.split(':')
    var endAll = parseInt(end1[0]) * 60 + parseInt(end1[1])
    if (endAll > startAll) {
      var c = endAll - startAll + ' ' + '分钟'
    } else {
      return 0 + ' ' + '分钟'
    }
    return c
  }
}
/** 计算来个日期的间隔
 * **/
export function t_parseTime_between(startTime,endTime) {

   if(!startTime || !endTime){
     return 0
   }
  var  betweenTIime= endTime-startTime
  return  (betweenTIime/1000/24/3600).toFixed()
}

/** 计算某个日几天后的日期你
 * **/
export function t_parseTime_num(time, num, cFormat = '{y}-{m}-{d}') {

  var newtime = time + num * 24 * 3600 * 1000
  return parseTime(newtime, cFormat)
}
/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"')
      .replace(/\+/g, ' ') +
    '"}'
  )
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在,重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

// 替换邮箱字符
export function regEmail(email) {
  if (String(email).indexOf('@') > 0) {
    const str = email.split('@')
    let _s = ''
    if (str[0].length > 3) {
      for (var i = 0; i < str[0].length - 3; i++) {
        _s += '*'
      }
    }
    var new_email = str[0].substr(0, 3) + _s + '@' + str[1]
  }
  return new_email
}

// 替换手机字符
export function regMobile(mobile) {
  if (mobile.length > 7) {
    var new_mobile = mobile.substr(0, 3) + '****' + mobile.substr(7)
  }
  return new_mobile
}

// 下载文件
export function downloadFile(obj, name, suffix) {
  const url = window.URL.createObjectURL(new Blob([obj]))
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  const fileName = parseTime(new Date()) + '-' + name + '.' + suffix
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
/** 获取不同的时间**/
export function getLastTime (cur,type) { //cur 当前时间 type  类型, 1月初,2月末

  //月初
  var firstDay = new Date(cur.getFullYear() + '/' + (cur.getMonth() + 1) + '/' + cur.getDate() + ' 00:00:00');
  //月末
  var lastDay = new Date(+firstDay);
  lastDay.setMonth(lastDay.getMonth() + 1);
  //
//上月月初
  var firstmouth=new Date(firstDay)
  firstmouth.setMonth(firstmouth.getMonth()-1);
  //上月月末
  var lastmouth =new Date(lastDay)
  lastmouth.setMonth(lastmouth.getMonth()-1);
  //上月当天
  var newlastmouth =new Date(firstDay)
  newlastmouth.setMonth(lastmouth.getMonth()-1);
  //上年当天
  var newlastyear =new Date(firstDay)
  newlastyear.setFullYear(newlastyear.getFullYear()-1);

  //今年年初
  var firstyear =new Date(firstDay)
  firstyear.setFullYear(firstyear.getFullYear());
  firstyear.setMonth(0);
  firstyear.setDate(1);
  //今年年未
  var lasttyear =new Date(lastDay)
  lasttyear.setFullYear(lasttyear.getFullYear());
  lasttyear.setMonth(12);
  lasttyear.setDate(0);
  //去年年初
  var oldfirstyear =new Date(firstyear)
  oldfirstyear.setFullYear(oldfirstyear.getFullYear()-1);

  //去年年末
  var oldliastyear =new Date(lasttyear)
  oldliastyear.setFullYear(oldliastyear.getFullYear()-1);

  //上年当月月初
  var yearmouthFirst =new Date(firstDay)
  yearmouthFirst.setFullYear(yearmouthFirst.getFullYear()-1);
  yearmouthFirst.setDate(1);
 /* console.log('月初', parseTime(firstDay.setDate(1)))
  console.log('月末', parseTime(lastDay.setDate(0)))
  console.log('上月初', parseTime(firstmouth.setDate(1) ))
  console.log('上月末', parseTime(lastmouth.setDate(0)))
  console.log('上月当天', parseTime(newlastmouth))
  console.log('上年当天', parseTime(newlastyear))
  console.log('今年年初', parseTime(firstyear))
  console.log('今年年末', parseTime(lasttyear))
  console.log('上年年初', parseTime(oldfirstyear))

  console.log('上年年未', parseTime(oldliastyear))
  console.log('上年当月月初', parseTime(yearmouthFirst))*/
  debugger
  return {

        mouthNowFirst:firstDay.setDate(1),//月初
        mouthNowLast:firstDay.setDate(0),//月末
        mouthOldFirst:firstmouth.setDate(1),//上月月初
        mouthOldLast:lastmouth.setDate(0),//上月月末
        mouthOld:newlastmouth.getTime(),//上月当日
        yearOld:newlastyear.getTime(),//上年当日
        yearNowFirst:firstyear.getTime(),// 今年年初
        yearNowLast:lasttyear.getTime(),//今年年末


        yearOldFirst:oldfirstyear.getTime(),//上年年初
        yearOldLast:oldliastyear.getTime(),//上年年末

        yearmouthFirst:yearmouthFirst.getTime(),//上年当月月初


  }



}

二、组件的封装

<template>
  <el-date-picker
    class="filter-item"
    value-format="yyyy-MM-dd HH:mm:ss"
    v-model="value"
    type="daterange"
    align="right"
    unlink-panels
    @change="setSearch"
    range-separator="-"
    :start-placeholder="label"
    :end-placeholder="label"
    :picker-options="pickerOptions">
  </el-date-picker>
</template>

<script>
import { getLastTime,parseTime } from '@/utils/index'
var tiem=getLastTime(new Date(),3)
export default {
  props: {
    value: String,
    // selectValue: Array,
    label:String,
    isnew: {
      type:Number,
      required: 0
    },
  },
  name: 'picker',
  data() {
    return {
      // value2: [],
      pickerOptions:"",
      // beginDate: '',
      // endDate: '',
    }
  },
  // created () {
  //   this.beginDate = this.handleTimeOld(new Date()) //2012-12-1   handleTimeOld是我用来获取当月的第一天的
  //   this.endDate = this.handleTimeNew(new Date()) //2012-12-1 handleTimeNew是获取今天的日期
  //   this.value2.push(this.beginDate)
  //   this.value2.push(this.endDate)
  //   this.value = this.value2;
  //
  // },
  mounted(){

    this.getpickerOptions()
    if(this.isnew==1){

      this.value=[parseTime(tiem.mouthNowFirst,'{y}-{m}-{d} {h}:{i}:{s}'),`${parseTime(new Date().getTime(),'{y}-{m}-{d}')} 11:59:59`]
      this.$emit('input', this.value)
    }
    if(this.isnew==2){
      debugger
      this.value=[`${parseTime(new Date().getTime(),'{y}-{m}-{d}')} 00:00:00`,`${parseTime(new Date().getTime(),'{y}-{m}-{d}')} 11:59:59`]

      this.$emit('input', this.value)
    }
  },

  methods: {

    // handleTimeOld (time, split) {
    //   //是我用来获取当月的第一天的
    //   let date = new Date(time)
    //   let year = date.getFullYear()
    //   let month = date.getMonth() + 1
    //   split = '-'
    //   return [year, month, 1].map(num => this.formatNumber(num)).join(split)
    //
    // },
    // handleTimeNew (time) {
    //   //handleTimeNew是获取今天的日期
    //   let date = new Date(time)
    //   let year = date.getFullYear()
    //   let month = (date.getMonth() + 1) > 10 ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))
    //   let day = date.getDate() > 10 ? date.getDate() : ('0' + date.getDate())
    //   return `${year}-${month}-${day}`
    // },
    // formatNumber(number) {
    //   return String(number)[1] ? String(number) : `0${number}`
    // },
    parseTime,
    getpickerOptions(){


      this. pickerOptions= {
        shortcuts: [
          {
            text: '本月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(tiem.mouthNowFirst);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '上月整月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(tiem.mouthOldFirst);
              end.setTime(tiem.mouthOldLast+86399000);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '上月同期',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(tiem.mouthOldFirst);
              end.setTime(tiem.mouthOld+86399000);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '上年同期',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(tiem.yearmouthFirst);
              end.setTime(tiem.yearOld+86399000);
              picker.$emit('pick', [start, end]);
            }
          },

          {
            text: '本年全年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(tiem.yearNowFirst);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '上年全年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              /* yearOldFirst:oldfirstyear.getTime(),//上年年初
      yearOldLast:oldliastyear.getTime(),//上年年末*/
              start.setTime(tiem.yearOldFirst);
              end.setTime(tiem.yearOldLast+86399000);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      }
    },
    setSearch(){
      this.$emit('input', this.value)
      this.$parent.crud.toQuery()
    },



  }

}
</script>

<style scoped>

</style>

三、页面组件的使用

 <rangePicker v-model="query.createTime" isnew="1"  label="创建时间" @change="crud.toQuery" style="width: 20%"></rangePicker>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值