常用函数封装汇总
常用函数封装
获取某日期若干个工作日后的日期
* 参数:
* time: [String] 给定日期 yyyy-MM-dd
* itervalByDay: [Number] 相隔工作日
* 返回:
* rq:[String] 匹配的日期yyyy-MM-dd
var getworkday = function(time, itervalByDay){
var str = time.split("-");
var date = getDate();
date.setUTCFullYear(str[0], str[1] - 1, str[2]);
date.setUTCHours(0, 0, 0, 0);
var millisceonds =date.getTime();
for(var i = 1; i <= itervalByDay; i++){
millisceonds += 24 * 60 * 60 * 1000;
date.setTime(millisceonds);
if(date.getDay() == 0 || date.getDay() == 6) i--;
}
var year = date.getFullYear();
var month = (date.getMonth() + 1);
var day = date.getDate();
var rq = year + "/" + month + "/" + day;
return rq;
}
格式化日期
* 参数:
* date: 时间戳 [Date]
* isTime: 是否返回具体时间 [Boolean]
* 返回:
* isTime: false => yyyy-MM-dd [String]
* isTime: true => yyyy-MM-dd HH-mm-ss [String]
const formatDate = (date, isTime) => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
let d = [year, month, day].map(_formatNumber).join('-')
if (isTime) {
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
const time = [hour, minute, second].map(_formatNumber).join(':')
d = `${d} ${time}`
}
return d
}
const _formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
解析身份证号码信息
* 参数:
* IdCard: [String] 身份证号码
* type: [Number] 1/2/3
* 返回:
* type:1 => birthday [String] 出生日期
* type:2 => sex [Number] 性别
* type:3 => age [Number] 年龄
formatIdCard (IdCard, type) {
if (type === 1) {
// 获取出生日期
var birthday = IdCard.substring(6, 10) + '-' + IdCard.substring(10, 12) '-' + IdCard.substring(12, 14)
return birthday
}
if (type === 2) {
// 获取性别
if (parseInt(IdCard.substr(16, 1)) % 2 === 1) {
return '1' // 男
} else {
return '2' // 女
}
}
if (type === 3) {
// 获取年龄
var ageDate = new Date()
var month = ageDate.getMonth() + 1
var day = ageDate.getDate()
var age = ageDate.getFullYear() - IdCard.substring(6, 10) - 1
if (IdCard.substring(10, 12) < month || IdCard.substring(10, 12) === mont&& IdCard.substring(12, 14) <= day) {
age++
}
if (age <= 0) {
age = 1
}
return age
}
}
微信小程序wx.request封装
* 1.输出完整接口日志
* 2.统一配置请求头、响应参数
* 3.统一管理请求响应操作(成功、失败、token等情况)
request ({
url,
header,
data = {},
code = 'errCode', // 接口返回的业务标识
method = 'POST',
dataType = 'json',
timeout = 10000,
success = () => {},
fail = () => {},
complete = () => {}
}) {
wx.showLoading({ title: '正在加载中', mask: true })
return wx.request({
url,
data,
method,
header: {
'content-type': 'application/json',
token: this.globalData.token,
...header,
},
timeout,
complete: res => {
wx.hideLoading()
console.log('');
console.group(`---- ${url} ----`)
console.log('Params', data)
console.log('Header', {
'content-type': 'application/json',
token: this.globalData.token,
...header,
})
console.log('Response', res)
console.info(`#### ${url} ####`)
console.groupEnd()
// token 问题
if (res.data && res.data.errMsg && (+res.data.errCode === 403 || res.data.errMsg.includes('授权过期请重新登录'))) {
return this.showError('登录过期,请重新登录', false, () => {
wx.reLaunch({
url: `/pages/tab-bar/my/index?errMsg=tokenTimeOut`
})
})
}
complete(res)
// // 返回错误信息
// if (res.data.state && res.data.state !== 'successful') {
// wx.showToast({ title: res.data.errMsg, icon: 'none' })
// fail(res.data)
// return
// }
// success(res.data)
// 返回成功
if (res.data && +res.data[code] === 1) {
if (res.data.state !== 'successful') {
wx.showToast({ title: res.data.errMsg, icon: 'none' })
fail(res.data)
return
}
return success(res.data)
}
// 返回错误信息
wx.showToast({ title: res.data.errMsg, icon: 'none' })
fail(res.data)
}
})
}
获取图片base64
* 参数:
* file {file object} 文件对象
* 返回:
* {Promise}
async function imgToBase64 (file) {
return new Promise(resolve => {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = e => {
const imgFile = e.target.result
resolve(imgFile)
}
})
}
图片压缩
* 原理: 把图片宽度、高度调小
* @param file {file object | file base64}
* @param {width, height}:压缩图片宽高
* @returns {Promise}
*
* Tip: 与imgToBase64()配合使用效果更佳
async function imgToCompressed (file, {
width,
height
}) {
if (typeof file === 'object') {
file = await imgToBase64(file)
}
return new Promise(resolve => {
var image = new Image()
image.src = file
image.onload = () => {
const _width = image.width
const _height = image.height
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
let data = ''
if (width && width > _width) {
width = _width
height = _height
} else {
// 等比例缩放
width = width || Math.floor(_width * height / _height)
height = height || Math.floor(width * _height / _width)
}
canvas.width = width
canvas.height = height
context.drawImage(image, 0, 0, width, height)
data = canvas.toDataURL('image/jpeg').replace('data:image/jpeg;base64,', '')
resolve(data)
}
})
}
本文来自博客园,作者:吴知木,转载请注明原文链接:https://www.cnblogs.com/zh1q1/p/15223389.html