uniapp,常用工具函数
/* 处理文件路径 */export default { //拨打电话
callPhone(phone) {
uni.makePhoneCall({
phoneNumber: phone //仅为示例
});
},
// 判断对象是否包含空值
/*
** @return flag
** @params 目标对象
*/
paramsValidate(params) {
let flag = true;
for (var key in params) {
if (params != '0' && !params) {
return false; // 终止程序
}
}
return flag;
},
// 日期2023-01-03转几小时前,刚刚文字
timeToWords(stringTime) {
if (stringTime) {
// 获取当前
var minute = 1000 * 60;
var hour = minute * 60;
var day = hour * 24;
var week = day * 7;
var month = day * 30;
var time1 = new Date().getTime(); //当前的时间戳
var time2 = Date.parse(new Date(stringTime)); //指定时间的时间戳
var time = time1 - time2;
var result = null;
if (time < 0) {
result = stringTime
} else if (time / month >= 1) {
result = parseInt(time / month) + "月前";
} else if (time / week >= 1) {
result = parseInt(time / week) + "周前";
} else if (time / day >= 1) {
result = parseInt(time / day) + "天前";
} else if (time / hour >= 1) {
result = parseInt(time / hour) + "小时前";
} else if (time / minute >= 1) {
result = parseInt(time / minute) + "分钟前";
} else {
result = "刚刚";
}
return result;
}
},
// 判断是否是json格式
isJSON(str) {
if (typeof str == "string") {
try {
var obj = JSON.parse(str)
if (typeof obj == "object" && obj) {
return true
} else {
return false
}
} catch (e) {
return false
}
}
},
// 电话号码加密
phonePas(string, type) {
if (string) {
let str = string.substring(3, 7)
return string.replace(str, '****')
}
},
checkPhone(phone) {
let check = /^(?:(?:\+|00)86)?1\d{9}$/g.test(phone);
return check
},
// 身份证校验
checkIdNumber(idNum) {
let c = /^\d{6}(18|19|20)\d{2}(0\d|10|11|12)(\d|30|31)\d{3}[\dXx]$/g.test(idNum);
return c
},
// 字符串截取,str,需要截取的字符串,num需要从第几位截取,endStr-结尾的字符串
substr(str, num, endStr) {
return `${str.substring(0,num)}${endStr}`
},
// 判断空对象
isEmpty(obj) {
return Object.keys(obj).length === 0
},
// 年月日转为日期格式
// 日期转换
formatYMD(data, format = '-') {
if (data) {
let time1 = data.split(' ')
let time = time1.replace('年', '-').replace('月', '-').replace('日', ' ')
let arr = time.split('-')
let y = arr
let m = arr < 10 ? `0${arr}` : arr
let r = arr < 10 ? `0${arr}` : arr
// 没有秒自动补全秒
if (time1.split(':').length < 3) {
return `${y}${format}${m}${format}${r}${time1?time1+':00':''}`
}
return `${y}${format}${m}${format}${r}${time1?time1:''}`
} else {
return null
}
},
// 日期格式转年月日
formatToYMD(data) {
if (data) {
let time1 = data.split(' ')
let time = time1.replace('-', '年').replace('-', '月')
let arr = time1.split('-')
let y = arr
let m = arr < 10 ? `${arr.split('0')}` : arr
let enr = arr
let r = enr.split('0') ? enr.split('0') : enr.split('0')
return `${y}年${m}月${r}日 ${time1?time1:''}`
} else {
return null
}
},
// 日期格式化
formatDate: function(dateA, format = 'yyyy-MM-dd HH:mm:ss', splitType = "-") {
console.log('dateA', dateA)
const dateB = new Date(dateA).toJSON();
const date = new Date(+new Date(dateB) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(
/\.[\d]{3}Z/, '')
let arr = date.split(" ")
let dates
switch (format) {
case 'yyyy-MM-dd HH:mm:ss':
dates = date
break
case 'yyyy-MM-dd':
// dates = arr
dates = arr.replace('-', splitType).replace('-', splitType)
break
case 'HH:mm:ss':
dates = arr
break
case 'yyyy-MM-dd HH:mm':
let arr2 = []
arr2.push(date.split(":"))
arr2.push(date.split(":"))
dates = arr2.join(":")
break
case 'MM-dd':
let newArr = arr.split('-')
let result = []
if (newArr.length === 3) {
newArr < 10 ? newArr = newArr.split('0') : newArr
newArr < 10 ? newArr = newArr.split('0') : newArr
result.push(newArr)
result.push(newArr)
dates = result.join(splitType)
}
break
case 'HH:mm':
let newArr2 = arr.split(':')
let arr3 = []
arr3.push(newArr2)
arr3.push(newArr2)
dates = arr3.join(':')
break
}
return dates
},
// 获取当前月的最后一天
getLastDay(year, month) {
const isLeapYear = ((year % 4) == 0) && ((year % 100) != 0) || ((year % 400) == 0)
const maxDays =
const middleDays =
month = Number(month)
if (month == 2) {
if (isLeapYear) {
return 29
} else {
return 28
}
} else if (maxDays.includes(month)) {
return 31
} else if (middleDays.includes(month)) {
return 30
}
},
// 删除对象属性值为空的属性,obj-传入的对象
removeProperty(obj) {
Object.keys(obj).forEach((item) => {
if (obj === '' || obj === undefined || obj === null || obj === 'null') {
Reflect.deleteProperty(obj,item)
}
})
return obj
},
// base64转path
base64ToPath(base64) {
return new Promise(function(resolve, reject) {
if (typeof window === 'object' && 'document' in window) {
base64 = base64.split(',')
var type = base64.match(/:(.*?);/)
var str = atob(base64)
var n = str.length
var array = new Uint8Array(n)
while (n--) {
array = str.charCodeAt(n)
}
return resolve((window.URL || window.webkitURL).createObjectURL(new Blob(, {
type: type
})))
}
var extName = base64.match(/data\:\S+\/(\S+);/)
if (extName) {
extName = extName
} else {
reject(new Error('base64 error'))
}
var fileName = Date.now() + '.' + extName
if (typeof plus === 'object') {
var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
bitmap.loadBase64Data(base64, function() {
var filePath = '_doc/uniapp_temp/' + fileName
bitmap.save(filePath, {}, function() {
bitmap.clear()
resolve(filePath)
}, function(error) {
bitmap.clear()
reject(error)
})
}, function(error) {
bitmap.clear()
reject(error)
})
return
}
if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
var filePath = wx.env.USER_DATA_PATH + '/' + fileName
wx.getFileSystemManager().writeFile({
filePath: filePath,
data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
encoding: 'base64',
success: function() {
resolve(filePath)
},
fail: function(error) {
reject(error)
}
})
return
}
reject(new Error('not support'))
})
}
}
function getLocalFilePath(path) {
if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf(
'_downloads') === 0) {
return path
}
if (path.indexOf('file://') === 0) {
return path
}
if (path.indexOf('/storage/emulated/0/') === 0) {
return path
}
if (path.indexOf('/') === 0) {
var localFilePath = plus.io.convertAbsoluteFileSystem(path)
if (localFilePath !== path) {
return localFilePath
} else {
path = path.substr(1)
}
}
return '_www/' + path
}
/* base64转文件路径 */
export function base64ToPath(base64) {
return new Promise(function(resolve, reject) {
if (typeof window === 'object' && 'document' in window) {
base64 = base64.split(',')
var type = base64.match(/:(.*?);/)
var str = atob(base64)
var n = str.length
var array = new Uint8Array(n)
while (n--) {
array = str.charCodeAt(n)
}
return resolve((window.URL || window.webkitURL).createObjectURL(new Blob(, {
type: type
})))
}
var extName = base64.match(/data\:\S+\/(\S+);/)
if (extName) {
extName = extName
} else {
reject(new Error('base64 error'))
}
var fileName = Date.now() + '.' + extName
if (typeof plus === 'object') {
var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
bitmap.loadBase64Data(base64, function() {
var filePath = '_doc/uniapp_temp/' + fileName
bitmap.save(filePath, {}, function() {
bitmap.clear()
resolve(filePath)
}, function(error) {
bitmap.clear()
reject(error)
})
}, function(error) {
bitmap.clear()
reject(error)
})
return
}
if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
var filePath = wx.env.USER_DATA_PATH + '/' + fileName
wx.getFileSystemManager().writeFile({
filePath: filePath,
data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
encoding: 'base64',
success: function() {
resolve(filePath)
},
fail: function(error) {
reject(error)
}
})
return
}
reject(new Error('not support'))
})
}
来源:https://www.cnblogs.com/zz151/p/17218763.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页:
[1]