记录一些常用js方法

123 阅读1分钟

当前日期前后

addByTransDate(dateParameter, num) {
	var translateDate = "",
		dateString = "",
		monthString = "",
		dayString = "";
	translateDate = dateParameter.replace("-", "/").replace("-", "/");;
	var newDate = new Date(translateDate);
	newDate = newDate.valueOf();
	newDate = newDate - num * 24 * 60 * 60 * 1000; //备注 如果是往前计算日期则为减号bai 否则为加号
	newDate = new Date(newDate);
	//如果月份长度少于2,则前加 0 补位
	if ((newDate.getMonth() + 1).toString().length == 1) {
		monthString = 0 + "" + (newDate.getMonth() + 1).toString();
	} else {
		monthString = (newDate.getMonth() + 1).toString();
	}
	//如果天数长度少于2,则前加 0 补位
	if (newDate.getDate().toString().length == 1) {
		dayString = 0 + "" + newDate.getDate().toString();
	} else {
		dayString = newDate.getDate().toString();
	}
	dateString = newDate.getFullYear() + "-" + monthString + "-" + dayString;
	return dateString;
}

例: addByTransDate('2021-11-02', 0);//2021-11-02

addByTransDate('2021-11-02', -1);//2021-11-03

addByTransDate('2021-11-02', 1);//2021-11-01

根据年月日获取星期

function getweekday(date) {
	var weekArray = new Array("日", "一", "二", "三", "四", "五", "六");
	var week = weekArray[new Date(date).getDay()]; //注意此处必须是先new一个Date
	return week;
}

例:getweekday('2021-11-01');//一

自动填充月份后面的天数

function fillDays(endDate) {
	var lastMonth;
	var endMonth = endDate.split('-')[1]; //获取传过来日期的月份
	var date = new Date;
	var nowMonth = date.getMonth() + 1;
	var nowday = date.getDate();
	nowMonth = nowMonth < 10 ? '0' + nowMonth : nowMonth;
	if (endMonth == nowMonth) {
		lastMonth = endDate.split('-')[0] + '-' + endDate.split('-')[1] + '-' + ((nowday - 1) < 10 ? '0' + (nowday -
			1) : (nowday - 1))
	} else {
		lastMonth = endDate + '-' + new Date(endDate.split('-')[0], endDate.split('-')[1],
			0).getDate()
	}
	return lastMonth
}

例:fillDays('2021-10');//2021-10-31

fillDays('2021-11');//2021-11-02本月的获取到当前日期的前一天

判断是否是企业微信浏览器

checkIsQv() {
	var ua = window.navigator.userAgent.toLowerCase()
	if (ua.indexOf('wxwork') >= 0 && ua.indexOf('micromessenger') >= 0) {
		return true
	}
	return false
}

获取地址后面的参数值

getUrlParam(name) {
	var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
	var r = window.location.search.substr(1).match(reg)
	if (r != null) return unescape(r[2])
	return null
}

例:getUrlParam("code");//当前地址中获取code值

千分位分隔符

numFormat(num) {
	var res = num.toString().replace(/\d+/, function(n) { // 先提取整数部分
		return n.replace(/(\d)(?=(\d{3})+$)/g, function($1) {
			return $1 + ",";
		});
	})
	return res;
}

例:numFormat(198655);//198,655