js处理时间

158 阅读3分钟

时间戳转换成日期时间


const formatTime = date => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : '0' + n
}


function js_date_time(unixtime) {
	var dateTime = new Date(parseInt(unixtime))
	var year = dateTime.getFullYear();
	var month = dateTime.getMonth() + 1;
	if (month < 10) {
		month = "0" + month
	}
	var day = dateTime.getDate();
	if (day < 10) {
		day = "0" + day
	}
	var hour = dateTime.getHours();
	var minute = dateTime.getMinutes();
	var second = dateTime.getSeconds();
	if (minute < 10) {
		minute = "0" + minute
	}
	var now = new Date();
	var now_new = Date.parse(now.toDateString()); //typescript转换写法
	var milliseconds = now_new - dateTime;
	var timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
	return timeSpanStr;
}

//时间戳转换成多长时间前
function js_news_date(unixtime) {
	var result;
	var minute = 1000 * 60;
	var hour = minute * 60;
	var day = hour * 24;
	var halfamonth = day * 15;
	var month = day * 30;
	var year = month * 12
	var now = new Date();
	var nowDay = now.getDate()
	var curTime = new Date(parseInt(unixtime)); //后端返回的是秒数
	var curDay = curTime.getDate()
	var diffValue = now - curTime;
	if (diffValue < 0) {
		return;
	}
	var monthC = diffValue / month;
	var weekC = diffValue / (7 * day);
	var dayC = diffValue / day;
	var hourC = diffValue / hour;
	var minC = diffValue / minute;
	if (monthC >= 1) {
		if (monthC == 1)
			result = "" + parseInt(monthC) + "月前";
		else {
			result = js_month(unixtime);
		}
	} else if (weekC >= 1) {
		if (weekC >= 1 && weekC < 4) {
			result = "" + parseInt(weekC) + "周前";
		} else if (weekC >= 4) {
			result = "1月前";
		}

	} else if (dayC >= 1 && weekC < 1) {
		result = "" + parseInt(dayC) + "天前";
	} else if (dayC < 1) {
		if (nowDay != curDay) {
			result = '1天前'
		} else {
			result = js_time(unixtime);
		}

	}
	return result;
}

//时间戳转换成月份
function js_month(unixtime) {
	var dateTime = new Date(parseInt(unixtime))
	var month = dateTime.getMonth() + 1;
	if (month < 10) {
		month = "0" + month
	}
	var day = dateTime.getDate();
	if (day < 10) {
		day = "0" + day
	}
	var now = new Date();
	var now_new = Date.parse(now.toDateString()); //typescript转换写法
	var milliseconds = now_new - dateTime;
	var monthSpanStr = month + '-' + day;
	return monthSpanStr;
}

//时间戳转换成时间
function js_time(unixtime) {
	var dateTime = new Date(parseInt(unixtime))
	var hour = dateTime.getHours();
	var minute = dateTime.getMinutes();
	var second = dateTime.getSeconds();
	if (minute < 10) {
		minute = "0" + minute
	}
	var now = new Date();
	var now_new = Date.parse(now.toDateString()); //typescript转换写法
	var timeStr = hour + ':' + minute;
	return timeStr;
}




//create code
function getWxCode() {
	return new Promise((resolve, reject) => {
		wx.login({ //code
			success: res => {
				resolve(res.code);
			},
			fail: err => {
				reject(err);
			}
		})
	})
}

function debounce(fn, interval) {
	var timer;
	var gapTime = interval || 1000;
	return function() {
		clearTimeout(timer);
		var context = this;
		var args = arguments;
		timer = setTimeout(function() {
			fn.call(context, args);
		}, gapTime);
	};
}

function isArray(obj) {
	return Object.prototype.toString.call(obj) === '[object Array]'
}


function toDown(num, s = 4) {
	var times = Math.pow(10, s)
	var des = num * times + 0.5
	des = parseInt(des, 10) / times
	return formatDecimal(des)
}


//函数节流
function throttle(fn, gapTime) {
	if (gapTime == null || gapTime == undefined) {
		gapTime = 1000
	}
	let _lastTime = null
	// 返回新的函数
	return function() {
		let _nowTime = +new Date()
		if (_nowTime - _lastTime > gapTime || !_lastTime) {
			fn.apply(this, arguments) //将this和参数传给原函数
			_lastTime = _nowTime
		}
	}
}
//立即支付函数节流
function payThrottle(fn, gapTime) {
	if (gapTime == null || gapTime == undefined) {
		gapTime = 5000
	}
	let _lastTime = null
	// 返回新的函数
	return function() {
		let _nowTime = +new Date()
		if (_nowTime - _lastTime > gapTime || !_lastTime) {
			fn.apply(this, arguments) //将this和参数传给原函数
			_lastTime = _nowTime
		}
	}
}

/**
 * 设置页面监听器 watch 在页面onLoad引入Utils.setWatcher(this)
 */
function setWatcher(page) {
	let data = page.data;
	let watch = page.watch;
	Object.keys(watch).forEach(v => {
		let key = v.split('.'); // 将watch中的属性以'.'切分成数组
		let nowData = data; // 将data赋值给nowData
		for (let i = 0; i < key.length - 1; i++) { // 遍历key数组的元素,除了最后一个!
			nowData = nowData[key[i]]; // 将nowData指向它的key属性对象
		}
		let lastKey = key[key.length - 1];
		// 假设key==='my.name',此时nowData===data['my']===data.my,lastKey==='name'
		let watchFun = watch[v].handler || watch[v]; // 兼容带handler和不带handler的两种写法
		let deep = watch[v].deep; // 若未设置deep,则为undefine
		observe(nowData, lastKey, watchFun, deep, page); // 监听nowData对象的lastKey
	})
}
/**
 * 监听属性 并执行监听函数
 */
function observe(obj, key, watchFun, deep, page) {
	var val = obj[key];
	// 判断deep是true 且 val不能为空 且 typeof val==='object'(数组内数值变化也需要深度监听)
	if (deep && val != null && typeof val === 'object') {
		Object.keys(val).forEach(childKey => { // 遍历val对象下的每一个key
			observe(val, childKey, watchFun, deep, page); // 递归调用监听函数
		})
	}
	let that = this;
	Object.defineProperty(obj, key, {
		configurable: true,
		enumerable: true,
		set: function(value) {
			watchFun.call(page, value, val); // value是新值,val是旧值
			val = value;
			if (deep) { // 若是深度监听,重新监听该对象,以便监听其属性。
				observe(obj, key, watchFun, deep, page);
			}
		},
		get: function() {
			return val;
		}
	})
}

//拼团倒计时(拼团结束时间)
function timeRemaining(newTime, endTime) {
	let residueObj = {};
	if (endTime - newTime > 0) {
		let time = (endTime - newTime) / 1000;
		let day = parseInt(time / (60 * 60 * 24));
		let hou = parseInt(time % (60 * 60 * 24) / 3600);
		let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
		let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
		residueObj.day = timeFormat(day)
		residueObj.hour = timeFormat(hou)
		residueObj.min = timeFormat(min)
		residueObj.sec = timeFormat(sec)
		residueObj.state = true
	} else { //活动已结束,全部设置为'00'
		residueObj.day = "00"
		residueObj.hour = "00"
		residueObj.min = "00"
		residueObj.sec = "00"
		residueObj.state = false
	}
	return residueObj
}



function setPrice(num) {
	var a = parseInt(num)
	var b = (num+'').split('.')[1]
	var obj = {price: a}
	if(b){
		obj.floats = '.'+b
	}else{
		obj.floats = ''
	}
	return obj
}


module.exports = {
	formatTime: formatTime,
	getWxCode,
	js_date_time: js_date_time,
	js_month: js_month,
	js_time: js_time,
	js_news_date: js_news_date,
	debounce: debounce,
	isArray: isArray,
	toFixed: toFixed,
	throttle: throttle,
	payThrottle: payThrottle,
	formatRichText,
	formatDecimal,
	formatZero,
	upFixed,
	toDown,
	setWatcher,
	timeRemaining,
	countDownList,
	setPrice
}

取两位小数不四舍五入

function formatDecimal(num) {
	num = num.toString()
	let index = num.indexOf('.')
	if (index !== -1) {
		num = num.substring(0, index + 3)
	} else {
		num = num.substring(0)
	}
	return parseFloat(num).toFixed(2)
}

秒杀倒计时

function countDownList(newTime, start, end) {
	// 获取当前时间,同时得到活动结束时间数组
	let countDownArr = {};
	let startTime = timeRemaining(newTime, start)
	let endTime = timeRemaining(newTime, end)
	if (startTime.state) {
		countDownArr.text = "距活动开始"
		countDownArr.itext = "即将开始"
		countDownArr.iname = "countBefore"
		countDownArr.time = startTime
		countDownArr.code = '2' //秒杀未开始
	} else {
		countDownArr.time = endTime
		if (endTime.state) {
			countDownArr.text = "距活动结束"
			countDownArr.itext = "正在疯抢"
			countDownArr.iname = "countNow"
			countDownArr.code = '1' //秒杀中
		} else {
			countDownArr.text = "距活动结束"
			countDownArr.itext = "活动结束"
			countDownArr.iname = "countAfter"
			countDownArr.code = '4' //秒杀结束
		}

	}
	return countDownArr
}

处理金额精度的过滤函数

function toFixed(num, h = 0, s = 2) {
	var times = Math.pow(10, s)
	var des = num * times + 0.5
	des = parseInt(des, 10) / times
	if (h) {
		return parseFloat(parseFloat(des.toFixed(10)).toFixed(2)).toFixed(h)
	} else {
		return parseFloat(parseFloat(des.toFixed(10)).toFixed(2))
	}
}


处理富文本里的图片宽度自适应

/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.img标签添加style属性:max-width:100%;height:auto
 * 3.修改所有style里的width属性为max-width:100%
 * 4.去掉<br/>标签
 * @param html
 * @returns {void|string|*}
 */
function formatRichText(html) {
	let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
		return match;
	});
	newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	newContent = newContent.replace(/\<img/gi,
		'<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
	return newContent;
}