Utils常用方法

293 阅读2分钟

从前的车马邮件都很慢 人这辈子只用打一份工 现在信息技术高速发展的年代 我们打工人怎么能慢下来 让我们众志成城 埋头苦干 午安 打工人

格式化时间

  • 1970-01-01 08:00:00 自定义格式
/**
 * @description 格式化时间
 * @param time
 * @param cFormat
 * @returns {string|null}---2008-07-22 22:49:41
 */
 
 export function parseTime(time, cFormat) {
	if (arguments.length === 0) {
		return null
	}
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	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]
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}
  • 刚刚 几分钟前 几小时前 1月1日8时0分
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() +
			'分'
		)
	}
}
  • 上午好 下午好 晚上好
export function timeFix () {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}
  • 10位时间戳转换
export function tenBitTimestamp(time) {
	const date = new Date(time * 1000)
	const y = date.getFullYear()
	let m = date.getMonth() + 1
	m = m < 10 ? '' + m : m
	let d = date.getDate()
	d = d < 10 ? '' + d : d
	let h = date.getHours()
	h = h < 10 ? '0' + h : h
	let minute = date.getMinutes()
	let second = date.getSeconds()
	minute = minute < 10 ? '0' + minute : minute
	second = second < 10 ? '0' + second : second
	return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second
}
  • 13位时间戳转换
export function thirteenBitTimestamp(time) {
	const date = new Date(time / 1)
	const y = date.getFullYear()
	let m = date.getMonth() + 1
	m = m < 10 ? '' + m : m
	let d = date.getDate()
	d = d < 10 ? '' + d : d
	let h = date.getHours()
	h = h < 10 ? '0' + h : h
	let minute = date.getMinutes()
	let second = date.getSeconds()
	minute = minute < 10 ? '0' + minute : minute
	second = second < 10 ? '0' + second : second
	return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second
}

将url请求参数转为json格式

案例:http://127.0.0.1:8080/html/urltojson.html?id=1&name=good#&price=1234
在我们进入主题前,我先先看下获取网址URL的方法:
window.location.href //设置或获取整个URL为字符串-->
window.location.hash //设置或获取href属性中在井号#后面的参数--> #&price=1234
window.location.search //设置或获取href属性中跟在问号?后面,井号#前面的参数-->?id=1&name=good
/**
 * @description 将url请求参数转为json格式
 * @param url
 * @returns {id: "1", name: "good#", price: "1234"}
 */
export function paramObj(url) {
	const search = url.split('?')[1]
	if (!search) {
		return {}
	}
	return JSON.parse(
		'{"' +
		decodeURIComponent(search)
		.replace(/"/g, '\\"')
		.replace(/&/g, '","')
		.replace(/=/g, '":"')
		.replace(/\+/g, ' ') +
		'"}'
	)
}

父子关系的数组转换成树形结构数据

当然在实际开发中,可能属性名称的定义跟我例子中的不同,使用该方法的话,就需将属性名改成实际的名称即可,关键的属性名有id,parentId,childrens

树形结构.png

/**
 * @description 父子关系的数组转换成树形结构数据
 * @param data
 * @returns {*}
 */
export function translateDataToTree(data) {
	const parent = data.filter(
		(value) => value.parentId === 'undefined' || value.parentId == null
	)
	const children = data.filter(
		(value) => value.parentId !== 'undefined' && value.parentId != null
	)
	const translator = (parent, children) => {
		parent.forEach((parent) => {
			children.forEach((current, index) => {
				if (current.parentId === parent.id) {
					const temp = JSON.parse(JSON.stringify(children))
					temp.splice(index, 1)
					translator([current], temp)
					typeof parent.children !== 'undefined' ?
						parent.children.push(current) :
						(parent.children = [current])
				}
			})
		})
	}
	translator(parent, children)
	return parent
}

树形结构数据转换成父子关系的数组

/**
 * @description 树形结构数据转换成父子关系的数组
 * @param data
 * @returns {[]}
 */
export function translateTreeToData(data) {
	const result = []
	data.forEach((item) => {
		const loop = (data) => {
			result.push({
				id: data.id,
				name: data.name,
				parentId: data.parentId,
			})
			const child = data.children
			if (child) {
				for (let i = 0; i < child.length; i++) {
					loop(child[i])
				}
			}
		}
		loop(item)
	})
	return result
}