utils

作者: 莫伊剑客 | 来源:发表于2021-05-06 14:14 被阅读0次

记录

// utils
/**
 * @file: getElapsedTime.js
 * @method getElapsedTime
 * @param {type} t - 指定的时间戳
 * @description: 根据指定的t,获取t距离现在过去了多少秒/分钟/小时/天/年
 * @author: chenxubin
 * @date: 2021/3/26
 */
export default function getElapsedTime(t) {
  let now = Date.now();
  let elapsed = now - t
  let result = ''
  let second = 1000;
  let minute = 60 * second;
  let hours = 60 * minute;
  let day = 24 * hours;
  let months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  let nowYear = new Date(now).getFullYear()
  let nowMonth = new Date(now).getMonth()
  //判断是不是闰年
  if ((nowYear % 4 === 0 && nowYear % 100 !== 0) || nowYear % 400 === 0) months[1] = 29;
  let month = Math.abs(new Date(t).getMonth() - nowMonth)
  let year = nowYear - new Date(t).getFullYear()

  if (year !== 0 && month >= 12) result = year + '年'
  else if (month !== 0 && Math.round(elapsed / day) >= months[nowMonth]) return month + '个月'
  else if (parse(day) !== 0) result = parse(day) + '天'
  else if (parse(hours) !== 0) result = parse(hours) + '小时'
  else if (parse(minute) !== 0) result = parse(minute) + '分钟'
  else if (parse(second) !== 0) result = parse(second) + '秒'
  else if (parse(1) !== 0) result = parse(1) + '毫秒'
  else result = '0毫秒'
  function parse(time) {
    return Math.round(elapsed / time)
  }
  return result;
}

/**
 * 获取数据类型
 * @param {*} obj 
 */
export const type = obj => {
  const toString = Object.prototype.toString;
  var map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  };
  if (obj instanceof Element) {
    return 'element';
  }
  return map[toString.call(obj)];
}

相关文章

网友评论

      本文标题:utils

      本文链接:https://www.haomeiwen.com/subject/fchddltx.html