Newer
Older
smartKitchenMiniProgram / common / utils.js
dutingting on 22 Nov 2022 12 KB 1.0.1
const isType = function (type) {
  return function (arg) {
    return Object.prototype.toString.call(arg) === `[object ${type}]`;
  };
};

export const isFunction = isType('Function');

export const isObject = isType('Object');

export const isString = isType('String');

export const isArray = isType('Array');

export const isDate = isType('Date');

/**
 * 为10以内的数字补0
 */
export function addZero(n) {
  if (n >= 10) {
    return n + '';
  } else if (n < 10 && n >= 0) {
    return '0' + n;
  } else {
    return n;
  }
}

// 数组去重
export function uniqueArray(arr) {
  return [...new Set(arr)];
}

// 节流
export function throttle(fn, delay = 200) {

  let isThrottled = false;
  let saveArgs = null;
  let saveThis = null;

  return function wrapper(...args) {
    if (isThrottled) {
      saveArgs = args;
      saveThis = this;
      return;
    }

    isThrottled = true;
    fn.apply(this, args);

    setTimeout(() => {
      isThrottled = false;
      if (saveArgs) {
        wrapper.apply(saveThis, saveArgs);
        saveArgs = saveThis = null;
      }
    }, delay);
  }
}

// 防抖
export function debounce(fn, delay = 200) {
  let timer = null;

  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

// 获取页面URL参数
export function getLocationParams(name) {
  const pages = getCurrentPages();
  const curPage = pages[pages.length - 1];
  return name ? curPage.options[name] : curPage.options;
}

export function stringToDate(str) {
  // 字符串必需符合以下规则:
  // 按照年月日时分秒顺序;
  // 至少需指定到日,日与时之间需要加空格;
  // 连接符只能是一个字符,只有日的或者最后一个的连接符可以省略。
  // 例如如:2018-01-2 00:0:3,2018年2月20日 12时30,2018-2-1。
  const reg = /^(\d{1,4})\D(0[^0]|1[012]|[^0])\D(0[^0]|[12]\d|3[01]|[^0])(?:[^\d\s])?(?:\s|$)(?:([01]\d|2[0-3]|[^0])|$)(?:\D|$)(?:([0-5]\d|[^0])|$)(?:\D|$)(?:([0-5]\d|[^0])|$)(?:\D|$)(?:(\d{1,3})|$)\D?$/;
  if (!reg.test(str)) {
    throw new Error('字符串格式错误');
  }
  let year = 0, month = 0, day = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0;
  str.replace(reg, (...arg) => {
    year = Number(arg[1]);
    month = Number(arg[2]) - 1;
    day = Number(arg[3]);
    if (arg[4]) {
      hours = Number(arg[4]);
    }
    if (arg[5]) {
      minutes = Number(arg[5]);
    }
    if (arg[6]) {
      seconds = Number(arg[6]);
    }
    if (arg[7]) {
      milliseconds = Number(arg[7]);
    }
  });
  return new Date(year, month, day, hours, minutes, seconds, milliseconds);
}

/**
 * 将时间转换成字符串
 *
 * format可选格式:
 * yyyy替换年,MM替换月,dd替换天,HH替换时,mm替换分,ss替换秒,都可缺省
 * 中间的间隔单位只能使用一个字符,单位都可缺省
 * 例如:yyyy年MM月dd日 HH时mm分ss秒,yyyy-MM-dd HH:mm:ss,MM dd HH, yyyyMMdd
 */
export function dateToString(date, format = 'yyyy-MM-dd HH:mm:ss') {
  if (!isDate(date)) {
    throw new Error("第一个参数请传入Date类型");
  }
  const reg = /^(y{4})?[^yMdHms]?(M{2})?[^yMdHms]?(d{2})?[^yMdHms]?\s?(H{2})?[^yMdHms]?(m{2})?[^yMdHms]?(s{2})?[^yMdHms]?$/;
  if (!reg.test(format)) {
    throw new Error("第二个参数请传入yyyy-MM-dd HH:mm:ss格式的字符串");
  }
  format = format.replace(reg, (...arg) => {
    let match = arg[0];
    if (arg[1]) {
      let year = date.getFullYear();
      match = match.replace(arg[1] + "", year + "");
    }
    if (arg[2]) {
      let month = addZero(date.getMonth() + 1);
      match = match.replace(arg[2] + "", month);
    }
    if (arg[3]) {
      let day = addZero(date.getDate());
      match = match.replace(arg[3] + "", day);
    }
    if (arg[4]) {
      let hour = addZero(date.getHours());
      match = match.replace(arg[4] + "", hour);
    }
    if (arg[5]) {
      let min = addZero(date.getMinutes());
      match = match.replace(arg[5] + "", min);
    }
    if (arg[6]) {
      let second = addZero(date.getSeconds());
      match = match.replace(arg[6] + "", second);
    }
    return match;
  });
  return format;
}

/**
 * 格式化时间格式字符串
 * 字符串规则以及format规则同stringToDate,dateToString函数
 */
export function formatDateString(str, format) {
  return dateToString(stringToDate(str), format);
}

export function timeToNow(time) {
  const dValue = Date.now() - stringToDate(time).valueOf();
  const minutes = dValue / 1000 / 60;
  const hour = minutes / 60;
  const day = hour / 24;
  const month = day / 30;
  let val = '';
  if (minutes < 1) {
    val = "刚刚";
  } else if (minutes < 60) {
    val = Math.round(minutes) + "分钟前";
  } else if (hour < 24) {
    val = Math.round(hour) + "小时前";
  } else if (month < 1) {
    val = Math.round(day) + "天前";
  } else {
    val = Math.round(month) + "月前";
  }
  return val;
}

// JS 计算两个时间戳相差年月日时分秒
export function calculateDiffTime(startTime, endTime, type = 3) {
	var runTime = parseInt(endTime - startTime)
	var year = Math.floor(runTime / 86400 / 365)
	runTime = runTime % (86400 * 365)
	var month = Math.floor(runTime / 86400 / 30)
	runTime = runTime % (86400 * 30)
	var day = Math.floor(runTime / 86400)
	runTime = runTime % 86400
	var hour = Math.floor(runTime / 3600)
	runTime = runTime % 3600
	var minute = Math.floor(runTime / 60)
	runTime = runTime % 60
	var second = runTime
	if (type === 1) { // 返回相差年数
		return year + '年'
	} else if (type === 2) { // 返回相差年数月数
		return year + '年' + month + '月'
	} else if (type === 3) { // 返回相差年数月数天数
		if(year < 1) {
			return month + '个月' + day + '天'
		}
		return year + '年' + month + '个月' + day + '天'
	} else { // 返回相差年数月数天数时分秒
		return year + '年' + month + '月' + day + '日' + hour + '时' + minute + '分' + second + '秒'
	}
}

//时间截取日期2021-12-22 13:12:12 截取成为2021-12-12
export function timeToDate(time) {
  // let time = time.split('-').join('/');
  if (time.indexOf(' ') !== -1) {
    return time.slice(0, time.indexOf(' '));
  } else {
    return time;
  }
}

//时间截取日期2021-12-22 13:12:12 截取成为2021-12-12
export function timeToTime(time) {
  return time.slice(11, 16);
}

//时间戳格式化 2019-08-26 形式
export function stamp2Date(value) {
  var b = new Date(value);
  var year = b.getFullYear() + '-';
  var month = (b.getMonth() + 1);
  var date = b.getDate();
  month = month < 10 ? '0' + (b.getMonth() + 1) + '-' : (b.getMonth() + 1) + '-';
  date = date < 10 ? '0' + (b.getDate()) : date;
  var str = String(year) + String(month) + String(date) + '';
  return str;
}

//深拷贝
export function deepCopy(data) {
  if (!Array.isArray(data) && !isObject(data)) {
    return data;
  } else if (Array.isArray(data)) {
    return data.map(item => deepCopy(item));
  } else if (isObject(data)) {
    let ret = {};
    Object.keys(data).forEach(key => {
      ret[key] = deepCopy(data[key]);
    });
    return ret;
  }
}

//去除字符串前后空格
function Trim(str){ 
  if (!String.prototype.trim){
    /*---------------------------------------
     * 清除字符串多余符号
     *---------------------------------------*/
    String.prototype.trim = function () { 
     return this.replace(/(^[\s\n\t]+|[\s\n\t]+$)/g, "");
    }
   }
  return str.trim(); 
}

/**
 * 生成一个唯一的字符串ID,每次执行结果必定不一样
 */
export function getUid() {
  const random = "0123456789abcdefghijklmnopqrstuvwxyz";
  let str = "";
  for (let i = 0; i < 4; i++) {
    str += random[getRandom(0, 35)];
  }
  return new Date().valueOf() + str;
}

/**
 * 生成 n - m 之间的随机数
 */
export function getRandom(n, m) {
  return Math.floor(Math.random() * (m - n + 1) + n);
}

export function getDateTime(value) {
	let time = new Date(value);
	let year = time.getFullYear();
	let month = (time.getMonth()+1);
	let date = time.getDate();
	let hour = time.getHours();
	let minute = time.getMinutes();
	let second = time.getSeconds();
	month = month < 10 ? '0'+ month : month;
	date = date < 10 ? '0'+ date : date;
	hour = hour < 10 ? '0'+ hour + ":" : hour + ":";
	minute = minute < 10 ? '0'+ minute : minute;
	// second = second < 10 ? '0'+ second : second;
	let str1 = String(year)+String(month)+String(date);
	let str2 = String(hour) + String(minute);
	return {
		str1,
		str2
	};
}

//获取当前时区
export function getCurrentZone() {
	var timezone = new Date().getTimezoneOffset() / 60 * -1;//获取时区; //目标时区时间,东八区   东时区正数 西市区负数
	return timezone;
}
 //获取当前时区名称
export function getZoneName() {
	var tmSummer = new Date(Date.UTC(2005, 6, 30, 0, 0, 0, 0));
	var so = -1 * tmSummer.getTimezoneOffset();
	var tmWinter = new Date(Date.UTC(2005, 12, 30, 0, 0, 0, 0));
	var wo = -1 * tmWinter.getTimezoneOffset();
	console.log(so + " " + wo);
	if (-660 == so && -660 == wo) return 'Pacific/Midway';
	if (-600 == so && -600 == wo) return 'Pacific/Tahiti';
	if (-570 == so && -570 == wo) return 'Pacific/Marquesas';
	if (-540 == so && -600 == wo) return 'America/Adak';
	if (-540 == so && -540 == wo) return 'Pacific/Gambier';
	if (-480 == so && -540 == wo) return 'US/Alaska';
	if (-480 == so && -480 == wo) return 'Pacific/Pitcairn';
	if (-420 == so && -480 == wo) return 'US/Pacific';
	if (-420 == so && -420 == wo) return 'US/Arizona';
	if (-360 == so && -420 == wo) return 'US/Mountain';
	if (-360 == so && -360 == wo) return 'America/Guatemala';
	if (-360 == so && -300 == wo) return 'Pacific/Easter';
	if (-300 == so && -360 == wo) return 'US/Central';
	if (-300 == so && -300 == wo) return 'America/Bogota';
	if (-240 == so && -300 == wo) return 'US/Eastern';
	if (-240 == so && -240 == wo) return 'America/Caracas';
	if (-240 == so && -180 == wo) return 'America/Santiago';
	if (-180 == so && -240 == wo) return 'Canada/Atlantic';
	if (-180 == so && -180 == wo) return 'America/Montevideo';
	if (-180 == so && -120 == wo) return 'America/Sao_Paulo';
	if (-150 == so && -210 == wo) return 'America/St_Johns';
	if (-120 == so && -180 == wo) return 'America/Godthab';
	if (-120 == so && -120 == wo) return 'America/Noronha';
	if (-60 == so && -60 == wo) return 'Atlantic/Cape_Verde';
	if (0 == so && -60 == wo) return 'Atlantic/Azores';
	if (0 == so && 0 == wo) return 'Africa/Casablanca';
	if (60 == so && 0 == wo) return 'Europe/London';
	if (60 == so && 60 == wo) return 'Africa/Algiers';
	if (60 == so && 120 == wo) return 'Africa/Windhoek';
	if (120 == so && 60 == wo) return 'Europe/Amsterdam';
	if (120 == so && 120 == wo) return 'Africa/Harare';
	if (180 == so && 120 == wo) return 'Europe/Athens';
	if (180 == so && 180 == wo) return 'Africa/Nairobi';
	if (240 == so && 180 == wo) return 'Europe/Moscow';
	if (240 == so && 240 == wo) return 'Asia/Dubai';
	if (270 == so && 210 == wo) return 'Asia/Tehran';
	if (270 == so && 270 == wo) return 'Asia/Kabul';
	if (300 == so && 240 == wo) return 'Asia/Baku';
	if (300 == so && 300 == wo) return 'Asia/Karachi';
	if (330 == so && 330 == wo) return 'Asia/Calcutta';
	if (345 == so && 345 == wo) return 'Asia/Katmandu';
	if (360 == so && 300 == wo) return 'Asia/Yekaterinburg';
	if (360 == so && 360 == wo) return 'Asia/Colombo';
	if (390 == so && 390 == wo) return 'Asia/Rangoon';
	if (420 == so && 360 == wo) return 'Asia/Almaty';
	if (420 == so && 420 == wo) return 'Asia/Bangkok';
	if (480 == so && 420 == wo) return 'Asia/Krasnoyarsk';
	if (480 == so && 480 == wo) return 'Asia/Shanghai';//return 'Australia/Perth';
	if (540 == so && 480 == wo) return 'Asia/Irkutsk';
	if (540 == so && 540 == wo) return 'Asia/Tokyo';
	if (570 == so && 570 == wo) return 'Australia/Darwin';
	if (570 == so && 630 == wo) return 'Australia/Adelaide';
	if (600 == so && 540 == wo) return 'Asia/Yakutsk';
	if (600 == so && 600 == wo) return 'Australia/Brisbane';
	if (600 == so && 660 == wo) return 'Australia/Sydney';
	if (630 == so && 660 == wo) return 'Australia/Lord_Howe';
	if (660 == so && 600 == wo) return 'Asia/Vladivostok';
	if (660 == so && 660 == wo) return 'Pacific/Guadalcanal';
	if (690 == so && 690 == wo) return 'Pacific/Norfolk';
	if (720 == so && 660 == wo) return 'Asia/Magadan';
	if (720 == so && 720 == wo) return 'Pacific/Fiji';
	if (720 == so && 780 == wo) return 'Pacific/Auckland';
	if (765 == so && 825 == wo) return 'Pacific/Chatham';
	if (780 == so && 780 == wo) return 'Pacific/Enderbury'
	if (840 == so && 840 == wo) return 'Pacific/Kiritimati';
	return 'Asia/Shanghai';
}