123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959 |
- /**
- * 通用函数
- */
- import i18n from '../locale/index.js';
- var config = require('./config.js');
- /**
- * 时间戳转为 xxxx-xx-xx xx:xx:xx 格式
- */
- function formatTime(time) {
- if (time == 0) {
- return '';
- }
- var dateTime = new Date(time * 1000);
- var year = dateTime.getFullYear();
- var month = dateTime.getMonth() + 1;
- var date = dateTime.getDate();
- var hour = dateTime.getHours();
- var minute = dateTime.getMinutes();
- var second = dateTime.getSeconds();
- return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second;
- }
- /**
- * 时间戳转为 xxxx.xx.xx xx:xx 格式
- */
- function formatMinuteTime(time) {
- if (time == 0) {
- return '';
- }
- var dateTime = new Date(time * 1000);
- var year = dateTime.getFullYear();
- var month = dateTime.getMonth() + 1;
- var date = dateTime.getDate();
- var hour = dateTime.getHours();
- var minute = dateTime.getMinutes();
- return year + '.' + month + '.' + date + ' ' + hour + ':' + minute;
- }
- function getFlatternDistance(lon1, lat1, lon2, lat2) {
- var DEF_PI = 3.14159265359; // PI
- var DEF_2PI = 6.28318530712; // 2*PI
- var DEF_PI180 = 0.01745329252; // PI/180.0
- var DEF_R = 6370693.5; // radius of earth
- var ew1, ns1, ew2, ns2;
- var dx, dy, dew;
- var distance; // 角度转换为弧度
- ew1 = lon1 * DEF_PI180;
- ns1 = lat1 * DEF_PI180;
- ew2 = lon2 * DEF_PI180;
- ns2 = lat2 * DEF_PI180; // 经度差
- dew = ew1 - ew2; // 若跨东经和西经180 度,进行调整
- if (dew > DEF_PI) dew = DEF_2PI - dew;
- else if (dew < -DEF_PI) dew = DEF_2PI + dew;
- dx = DEF_R * Math.cos(ns1) * dew; // 东西方向长度(在纬度圈上的投影长度)
- dy = DEF_R * (ns1 - ns2); // 南北方向长度(在经度圈上的投影长度)
- // 勾股定理求斜边长
- distance = Math.sqrt(dx * dx + dy * dy).toFixed(0);
- return Number(distance);
- }
- function formatDateTime(time) {
- var dateTime = new Date(time);
- var year = dateTime.getFullYear();
- var month = ('00' + (dateTime.getMonth() + 1)).substr(String(dateTime.getMonth() + 1).length);
- var date = ('00' + dateTime.getDate()).substr(String(dateTime.getDate()).length);
- var hour = ('00' + dateTime.getHours()).substr(String(dateTime.getHours()).length);
- var minute = ('00' + dateTime.getMinutes()).substr(String(dateTime.getMinutes()).length);
- var second = ('00' + dateTime.getSeconds()).substr(String(dateTime.getSeconds()).length);
- return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second;
- }
- /**
- * js简单对象转为url查询字符串key=value&
- */
- function obj2UrlQuery(obj) {
- var urlQurey = '';
- for (var key in obj) {
- urlQurey += key + '=' + obj[key] + '&';
- }
- if (urlQurey != '') urlQurey = urlQurey.substring(0, urlQurey.length - 1);
- return urlQurey;
- }
- function getQueryObject(url) {
- url = url == null ? window.location.href : url;
- const search = url.substring(url.lastIndexOf('?') + 1);
- const obj = {};
- const reg = /([^?&=]+)=([^?&=]*)/g;
- search.replace(reg, (rs, $1, $2) => {
- const name = decodeURIComponent($1);
- let val = decodeURIComponent($2);
- val = String(val);
- obj[name] = val;
- return rs;
- });
- return obj;
- }
- /**
- * 去掉 undefined/null, 返回默认值
- */
- function getDefaultValue(value, default_value) {
- if (value === undefined || value === null) {
- return default_value || '';
- }
- return value;
- }
- /**
- * 判断为空: undefined/null/空字符
- * 为空返回 true, 否则返回false
- */
- function isEmpty(value) {
- if (value === undefined || value === null || value === '' || value.trim() === '') return true;
- return false;
- } //防止多次点击
- function preventMultipleClick() {
- const app = getApp();
- if (app.globalData.preventClick) {
- app.globalData.preventClick = false;
- setTimeout(() => {
- app.globalData.preventClick = true;
- }, 1500);
- }
- }
- function alert(title, content, successCallBack) {
- uni.showModal({
- title: title || '',
- content: content || '',
- showCancel: false,
- success: successCallBack
- });
- }
- function loading() {
- uni.showLoading({
- title: i18n.t('正在加载数据')+'...',
- mask: true
- });
- }
- /**
- * 成功提示
- */
- function successToast(title, duration) {
- uni.showToast({
- title: title || i18n.t('成功'),
- icon: 'success',
- duration: duration || 1500,
- mask: true
- });
- }
- /**
- * 简单提示
- */
- function simpleToast(title, duration) {
- uni.showToast({
- title: title || i18n.t('成功'),
- icon: 'none',
- duration: duration || 1500
- });
- }
- /**
- * 手机号验证 简单匹配
- */
- function isPhone(phone) {
- return phone.match(/^1[0-9]{10}$/) != null;
- }
- /**
- * 检验字符串是否是纯数值 正数 小数
- */
- function isDigital(num) {
- //return num.match(/^[1-9]?\d+[.]?\d+$/) != null;
- return num.match(/^[0-9]?\d+[.]?\d+$/) != null;
- }
- /**
- * 选择并上传图片
- */
- function uploadImg(callback) {
- uni.chooseImage({
- count: 1,
- success: function(res) {
- var tempFilePaths = res.tempFilePaths;
- uni.uploadFile({
- url: config.API_UP_IMG_URL,
- filePath: tempFilePaths[0],
- //#ifdef MP-ALIPAY
- fileType: "image",
- //#endif
- name: 'imgFile',
- success: function(res1) {
- var rtDataObj = JSON.parse(res1.data);
- if (rtDataObj.code == 200) {
- callback(rtDataObj.data[0].url);
- } else {
- uni.showModal({
- title: i18n.t('错误'),
- content: i18n.t('上传图片错误')+'[' + rtDataObj.message + ']'
- });
- }
- }
- });
- }
- });
- }
- /**
- * 选择并上传图片 七牛存储
- */
- function upLoadImgQiNiu(callback, type = ['album', 'camera']) {
- const http = require('./http.js');
- uni.chooseImage({
- count: 1,
- sourceType: type,
- success: function(res) {
- const tempFilePaths = res.tempFilePaths;
- loading();
- http.getApi(config.API_QINIU_UP_IMG_TOKEN, {}, function(response) {
- if (response.data.code === 200) {
- const token = response.data.data.token;
- uni.uploadFile({
- url: config.QINIU_UPLOAD_SITE,
- filePath: tempFilePaths[0],
- //#ifdef MP-ALIPAY
- fileType: "image",
- //#endif
- name: 'file',
- formData: {
- token: token
- },
- success: function(res1) {
- uni.hideLoading();
- var rtDataObj = JSON.parse(res1.data);
- const key = rtDataObj.key;
- callback(config.QINIU_SITE + key);
- },
- fail: function(res) {
- simpleToast(i18n.t('上传失败'));
- uni.hideLoading();
- }
- });
- } else {
- simpleToast(response.data.msg);
- uni.hideLoading();
- }
- });
- }
- });
- }
- function getQVConfig(macid, successCallBack) {
- var pData = {
- macid: macid
- };
- const http = require('./http.js');
- http.postApi(config.API_QV_CONFIG, pData, function(response) {
- if (response.data.code === 200) {
- successCallBack(response);
- }
- });
- }
- function upLoadImgQiNiu2(callback, filePath) {
- const http = require('./http.js');
- loading();
- http.getApi(config.API_QINIU_UP_IMG_TOKEN, {}, function(response) {
- if (response.data.code === 200) {
- const token = response.data.data.token;
- uni.uploadFile({
- url: config.QINIU_UPLOAD_SITE,
- filePath: filePath,
- name: 'file',
- //#ifdef MP-ALIPAY
- fileType: "image",
- //#endif
- formData: {
- token: token
- },
- success: function(res1) {
- uni.hideLoading();
- var rtDataObj = JSON.parse(res1.data);
- const key = rtDataObj.key;
- callback(config.QINIU_SITE + key);
- },
- fail: function(res) {
- simpleToast(i18n.t('上传失败'));
- uni.hideLoading();
- }
- });
- } else {
- simpleToast(response.data.msg);
- uni.hideLoading();
- }
- });
- }
- /**
- * 判断一个元素是否在数组中
- */
- function inArray(elem, arrayData) {
- for (var i = 0; i < arrayData.length; i++) {
- if (elem == arrayData[i]) {
- return true;
- }
- }
- return false;
- }
- function compareVersion(v1, v2) {
- v1 = v1.split('.');
- v2 = v2.split('.');
- const len = Math.max(v1.length, v2.length);
- while (v1.length < len) {
- v1.push('0');
- }
- while (v2.length < len) {
- v2.push('0');
- }
- for (let i = 0; i < len; i++) {
- const num1 = parseInt(v1[i]);
- const num2 = parseInt(v2[i]);
- if (num1 > num2) {
- return 1;
- } else if (num1 < num2) {
- return -1;
- }
- }
- return 0;
- }
- /**
- * 格式化秒
- * @param int value 总秒数
- * @return string result 格式化后的字符串
- */
- function formatSeconds(value) {
- var theTime = parseInt(value); // 需要转换的时间秒
- var theTime1 = 0; // 分
- var theTime2 = 0; // 小时
- var theTime3 = 0; // 天
- if (theTime === 0) return parseInt(theTime) + '秒';
- if (theTime > 60) {
- theTime1 = parseInt(theTime / 60);
- theTime = parseInt(theTime % 60);
- if (theTime1 > 60) {
- theTime2 = parseInt(theTime1 / 60);
- theTime1 = parseInt(theTime1 % 60);
- if (theTime2 > 24) {
- //大于24小时
- theTime3 = parseInt(theTime2 / 24);
- theTime2 = parseInt(theTime2 % 24);
- }
- }
- }
- var result = '';
- if (theTime > 0) {
- result = '' + parseInt(theTime) + '秒';
- }
- if (theTime1 > 0) {
- result = '' + parseInt(theTime1) + '分' + result;
- }
- if (theTime2 > 0) {
- result = '' + parseInt(theTime2) + '小时' + result;
- }
- if (theTime3 > 0) {
- result = '' + parseInt(theTime3) + '天' + result;
- }
- return result;
- }
- function hueRotate(r, g, b, deg) {
- var components = [];
- var cosHue = Math.cos((deg * Math.PI) / 180);
- var sinHue = Math.sin((deg * Math.PI) / 180);
- components[0] = 0.213 + cosHue * 0.787 - sinHue * 0.213;
- components[1] = 0.715 - cosHue * 0.715 - sinHue * 0.715;
- components[2] = 0.072 - cosHue * 0.072 + sinHue * 0.928;
- components[3] = 0.213 - cosHue * 0.213 + sinHue * 0.143;
- components[4] = 0.715 + cosHue * 0.285 + sinHue * 0.14;
- components[5] = 0.072 - cosHue * 0.072 - sinHue * 0.283;
- components[6] = 0.213 - cosHue * 0.213 - sinHue * 0.787;
- components[7] = 0.715 - cosHue * 0.715 + sinHue * 0.715;
- components[8] = 0.072 + cosHue * 0.928 + sinHue * 0.072;
- var red = r * components[0] + g * components[1] + b * components[2];
- var green = r * components[3] + g * components[4] + b * components[5];
- var blue = r * components[6] + g * components[7] + b * components[8];
- return [red, green, blue];
- }
- function toArrayBuffer(arr) {
- var buffer = new ArrayBuffer(arr.length);
- var view = new Int8Array(buffer);
- for (var i = 0; i < arr.length; i++) {
- view[i] = arr[i];
- }
- return buffer;
- }
- function completArrayCRC(arr, n = 16) {
- for (var i = n - arr.length; i > 1; i--) {
- arr.push(0);
- }
- arr.push(arr.reduce((p, c) => p + c) % 0x100);
- return arr;
- }
- function getRamNumber() {
- var result = '';
- for (var i = 0; i < 8; i++) {
- result += Math.floor(Math.random() * 16).toString(16); //获取0-15并通过toString转16进制
- } //默认字母小写,手动转大写
- return result.toUpperCase(); //另toLowerCase()转小写
- }
- function checkVersion() {
- // 获取小程序更新机制的兼容,由于更新的功能基础库要1.9.90以上版本才支持,所以此处要做低版本的兼容处理
- if (uni.canIUse('getUpdateManager')) {
- // wx.getUpdateManager接口,可以获知是否有新版本的小程序、新版本是否下载好以及应用新版本的能力,会返回一个UpdateManager实例
- const updateManager = uni.getUpdateManager(); // 检查小程序是否有新版本发布,onCheckForUpdate:当小程序向后台请求完新版本信息,会通知这个版本告知检查结果
- updateManager.onCheckForUpdate(function(res) {
- // 请求完新版本信息的回调
- if (res.hasUpdate) {
- // 检测到新版本,需要更新,给出提示
- uni.showModal({
- title: '更新提示',
- content: '检测到新版本,是否下载新版本并重启小程序',
- success: function(res) {
- if (res.confirm) {
- // 用户确定更新小程序,小程序下载和更新静默进行
- _this.downLoadAndUpdate(updateManager);
- } else if (res.cancel) {
- // 若用户点击了取消按钮,二次弹窗,强制更新,如果用户选择取消后不需要进行任何操作,则以下内容可忽略
- uni.showModal({
- title: '提示',
- content: '本次版本更新涉及到新功能的添加,旧版本将无法正常使用',
- showCancel: false,
- // 隐藏取消按钮
- confirmText: '确认更新',
- // 只保留更新按钮
- success: function(res) {
- if (res.confirm) {
- // 下载新版本,重启应用
- downLoadAndUpdate(updateManager);
- }
- }
- });
- }
- }
- });
- }
- });
- } else {
- // 在最新版本客户端上体验小程序
- uni.showModal({
- title: '提示',
- content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试'
- });
- }
- } // 下载小程序最新版本并重启
- function downLoadAndUpdate(updateManager) {
- uni.showLoading(); // 静默下载更新小程序新版本,onUpdateReady:当新版本下载完成回调
- updateManager.onUpdateReady(function() {
- uni.hideLoading(); // applyUpdate:强制当前小程序应用上新版本并重启
- updateManager.applyUpdate();
- }); // onUpdateFailed:当新版本下载失败回调
- updateManager.onUpdateFailed(function() {
- // 下载新版本失败
- uni.showModal({
- title: '已有新版本',
- content: '新版本已经上线了,请删除当前小程序,重新搜索打开'
- });
- });
- }
- function getASCIICode(text) {
- var index = 0,
- out = new Array(),
- show = [];
- if (text.length) {
- while (index < text.length) {
- var character = text.charAt(index),
- charCode = text.charCodeAt(index);
- if (charCode >= 0xd800 && charCode <= 0xdbff) {
- ++index;
- out.push(new Array(character + text.charAt(index), charCode.toString(16).toUpperCase() + text
- .charCodeAt(index).toString(16).toUpperCase()));
- } else {
- out.push(new Array(character, charCode.toString(16).toUpperCase()));
- }
- ++index;
- }
- for (var x in out) {
- var D = parseInt(out[x][1], 16);
- if (D > 65535) {
- //超出ascii utf16
- } else if (D > 127) {
- //超出ascii unicode
- } //show += out[x][1]
- else show.push(D);
- }
- }
- return show;
- }
- function bluetoothGetCtlData() {
- const http = require('./http.js');
- const accountInfo = uni.getAccountInfoSync();
- const app = getApp();
- http.postApi(
- config.API_GET_CTL, {
- appid: accountInfo.miniProgram.appId
- },
- (resp) => {
- if (resp.data.code === 200) {
- app.globalData.bluetoothConfig = resp.data.data;
- }
- }
- );
- }
- function getHexData(data) {
- var hexStr = '';
- for (var i = 0; data.length > i; i++) {
- var hex = data[i].toString(16);
- if (hex.length === 1) {
- hex = '0' + hex;
- }
- hexStr = hexStr + hex;
- }
- return hexStr;
- }
- var repeatTime = 0;
- function reportBms(macid, data, successCallBack) {
- var pData = {
- macid: macid,
- data: getHexData(data)
- };
- const http = require('./http.js');
- var endTime = new Date().getTime();
- if (endTime - repeatTime > 3000) {
- //防止多条数据重发
- repeatTime = endTime;
- http.postApi(config.API_REPORT_BMS, pData, function(response) {
- if (response.data.code === 200) {
- successCallBack(response);
- }
- });
- }
- }
- function reportLog(type, dev_id, data) {
- var pData = {
- dev_id: dev_id,
- origin: type,
- data: data
- };
- const http = require('./http.js');
- http.postApi(config.API_CABINET_BLUETOOTH_LOG, pData, function(response) {});
- }
- function maskPhoneNumber(phoneNumber) {
- // 确保输入的是字符串
- phoneNumber = phoneNumber.toString();
- // 使用正则表达式替换手机号中间的数字为 *
- var maskedPhoneNumber = phoneNumber.replace(/(\d{3})\d+(\d{4})/, "$1****$2");
- return maskedPhoneNumber;
- }
- function formatDistance(distanceMeters) {
- if (!distanceMeters) return ''
- // 判断距离是否超过1000米
- if (distanceMeters >= 1000) {
- // 如果超过1000米,则转换为千米并返回
- return (distanceMeters / 1000).toFixed(2) + 'km';
- } else {
- // 否则直接返回米
- return distanceMeters.toFixed(0) + 'm';
- }
- }
- function formatWeight(weightMeters) {
- if (!weightMeters) return ''
- if (weightMeters >= 1000) {
- return (weightMeters / 1000).toFixed(2) + 'kg';
- } else {
- return weightMeters.toFixed(0) + 'g';
- }
- }
- function loadAugmentTime(duration_unit, time, select_hire_duration) {
- // (周期单位,开始时间, 周期)
- var now = new Date(time);
- switch (duration_unit - 0) {
- case 1: //日
- now = new Date(now.getTime() + select_hire_duration * 24 * 60 * 60 * 1000);
- break;
- case 2:
- now.setMonth(now.getMonth() + select_hire_duration);
- break;
- case 3:
- now.setFullYear(now.getFullYear() + select_hire_duration);
- break;
- case 4: //时
- var cycle_time = select_hire_duration / 24;
- now = new Date(now.getTime() + cycle_time * 24 * 60 * 60 * 1000);
- break;
- case 5:
- var cycle_time = select_hire_duration;
- now = new Date(now.getTime() + cycle_time * 60 * 1000);
- break;
- case 6: //周
- var cycle_time = select_hire_duration * 7;
- now = new Date(now.getTime() + cycle_time * 24 * 60 * 60 * 1000);
- break;
- }
- return parseInt(now.getTime() / 1000);
- }
- function isObjectEmpty(obj) {
- for (var key in obj) {
- if (obj.hasOwnProperty(key))
- return false;
- }
- return true;
- }
- function formatDate(dateStr) { // yyyy-mm-dd转换mm月dd日
- const date = new Date(dateStr);
- const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,所以加1
- const day = String(date.getDate()).padStart(2, '0'); // 日期不足两位时前面补0
- return `${month}月${day}日`;
- }
- function formatTimeDate(datetime) { // 时间戳格式化 返回x月x日 x:x
- if (datetime == 0) {
- return '';
- }
- var date = new Date(datetime * 1000);
- var month = String(date.getMonth() + 1).padStart(2, '0')
- var day = String(date.getDate()).padStart(2, '0')
- var hour = String(date.getHours()).padStart(2, '0')
- var minute = String(date.getMinutes()).padStart(2, '0')
- return month + '月' + day + '日 ' + ' ' + hour + ':' + minute;
- }
- function getToDay(type) { //转化为yyyy-mm-dd
- if (type === 1) {
- const now = new Date();
- const year = now.getFullYear();
- const month = String(now.getMonth() + 1).padStart(2, '0');
- const day = String(now.getDate() - 0 + 1).padStart(2, '0');
- const formattedDate = `${year}-${month}-${day}`;
- return formattedDate;
- } else {
- const now = new Date();
- const year = now.getFullYear();
- const month = String(now.getMonth() + 1).padStart(2, '0');
- const day = String(now.getDate()).padStart(2, '0');
- const formattedDate = `${year}-${month}-${day}`;
- return formattedDate;
- }
- }
- function getTimeToDay(time) { //转化为天时分
- if (time > 0) {
- var day = Math.floor(time / (60 * 24))
- var hour = Math.floor((time - day * (60 * 24)) / 60)
- var Minute = Math.floor(time - (hour * 60) - day * (60 * 24))
- var timeToDay = {
- day: day,
- hour: hour,
- minute: Minute,
- }
- } else {
- timeToDay = ''
- }
- return timeToDay
- }
- //判断当前时间是否在时间段内 店铺是否营业
- function isWithinTimeRange(startTime, endTime) {
- // 获取当前时间
- const now = new Date();
- const currentMinutes = now.getHours() * 60 + now.getMinutes();
- // 将传入的时间转换为分钟
- const [startHour, startMinute] = startTime.split(':').map(Number);
- const [endHour, endMinute] = endTime.split(':').map(Number);
- const startMinutes = startHour * 60 + startMinute;
- const endMinutes = endHour * 60 + endMinute;
- // 判断当前时间是否在指定范围内
- return currentMinutes >= startMinutes && currentMinutes <= endMinutes;
- }
- // 时间戳格式化 x:x:x -> x:x
- var formatToHHMM = function(timeStr) {
- var data = timeStr.split(':')
- var hours = data[0];
- var minutes = data[1];
- return hours + ':' + minutes;
- }
- // 时间戳格式化 x:x:x -> x:x
- var hideProvinceAndCity = function(address) {
- var regex = /(?:[\u4e00-\u9fa5]+省|[\u4e00-\u9fa5]+市|[\u4e00-\u9fa5]+自治区|[\u4e00-\u9fa5]+特别行政区)/g;
- return address.replace(regex, '').replace(/\s+/g, '').trim();
- }
- function calculateRemainingTime(serverTimestamp) {
- const currentTimestamp = getCurrentTimestamp();
- const remainingTime = serverTimestamp - currentTimestamp;
- return remainingTime > 0 ? remainingTime : 0;
- }
- function formatTimeScan(seconds) {
- const hours = Math.floor(seconds / 3600);
- const minutes = Math.floor((seconds % 3600) / 60);
- const secs = seconds % 60;
- var timeStr = ""
- return {
- hours: String(hours).padStart(2, '0'),
- minutes: String(minutes).padStart(2, '0'),
- secs: String(secs).padStart(2, '0')
- }
- }
- function getFormattedTime(time) {
- // 获取当前时间
- const now = time ? time : new Date();
- // 加上30分钟
- now.setMinutes(now.getMinutes() + 30);
- // 格式化时间
- const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从0开始,需要加1
- const day = String(now.getDate()).padStart(2, "0"); // 日期
- const hours = String(now.getHours()).padStart(2, "0"); // 小时
- const minutes = String(now.getMinutes()).padStart(2, "0"); // 分钟
- // 拼接成目标格式
- return `${month}-${day} ${hours}:${minutes}`;
- }
- function countToDay(count, unit) {
- let data = '';
- switch (unit - 0) {
- case 1: //日
- data = count
- break;
- case 2: //月
- data = count * 30
- break;
- case 3: //年
- data = count * 365
- break;
- case 4: //时
- data = count
- break;
- case 6: //周
- data = count * 7
- break;
- case 7: //季
- data = count * 90
- break;
- }
- return data;
- }
- async function callPhone(phone) {
- const text = i18n.t('您是否要拨打电话' + phone + '?')
- // const text=that.$t()+phone+'?'
- let res = await uni.showModal({
- content: text,
- confirmText: i18n.t('确定'),
- })
- if (res[1].confirm) {
- uni.makePhoneCall({
- phoneNumber: phone,
- })
- }
- }
- function timestampToDays(timestamp) {
- if (!timestamp) return
- // 1秒 = 1000毫秒,1分钟 = 60秒,1小时 = 60分钟,1天 = 24小时
- const millisecondsInADay = 24 * 60 * 60 * 1000;
- // 计算天数
- const days = timestamp / millisecondsInADay;
- // 保留一位小数
- return days.toFixed(1);
- }
- //计算相差时间
- function formatTimeDifference(timestamp) {
- const current = Date.now();
- const diff = Math.abs(current - timestamp);
- const totalHours = diff / (1000 * 60 * 60)
- let days = 0;
- let hours;
- if (totalHours >= 24) {
- days = Math.floor(totalHours / 24); // 计算完整天数
- hours = Math.round(totalHours % 24); // 剩余小时四舍五入
-
- const result = [];
- if (days > 0) result.push(`${days + i18n.t('天')}`);
- if (hours > 0 || result.length === 0) result.push(`${hours + i18n.t('小时')}`);
- return result.join("");
-
- } else {
- // 提取整数小时部分
- hours = Math.floor(totalHours);
- // 计算剩余的小数小时并转换为分钟
- let remaining = totalHours - hours;
- let minutes = Math.round(remaining * 60);
- // 处理分钟进位(例如 59.6分钟 → 60分钟 → 进位到小时)
- if (minutes >= 60) {
- hours += 1;
- minutes = 0;
- }
- days = 0;
- if (hours) {
- return `${hours + i18n.t('小时')} ${minutes + i18n.t('分钟')}`;
- }else {
- return `${minutes + i18n.t('分钟')}`;
- }
-
- }
-
- }
- module.exports = {
- formatTime: formatTime,
- obj2UrlQuery: obj2UrlQuery,
- getQueryObject: getQueryObject,
- getDefaultValue: getDefaultValue,
- isEmpty: isEmpty,
- alert: alert,
- isPhone: isPhone,
- loading: loading,
- successToast: successToast,
- simpleToast: simpleToast,
- isDigital: isDigital,
- uploadImg: uploadImg,
- upLoadImgQiNiu: upLoadImgQiNiu,
- upLoadImgQiNiu2: upLoadImgQiNiu2,
- inArray: inArray,
- compareVersion: compareVersion,
- formatDateTime: formatDateTime,
- formatSeconds: formatSeconds,
- hueRotate: hueRotate,
- toArrayBuffer: toArrayBuffer,
- getASCIICode: getASCIICode,
- completArrayCRC: completArrayCRC,
- getFlatternDistance: getFlatternDistance,
- checkVersion: checkVersion,
- bluetoothGetCtlData: bluetoothGetCtlData,
- reportBms: reportBms,
- getQVConfig: getQVConfig,
- reportLog: reportLog,
- preventMultipleClick: preventMultipleClick,
- maskPhoneNumber: maskPhoneNumber,
- formatDistance: formatDistance,
- formatWeight: formatWeight,
- formatMinuteTime: formatMinuteTime,
- loadAugmentTime: loadAugmentTime,
- formatDate: formatDate,
- formatTimeDate: formatTimeDate,
- getToDay: getToDay,
- getTimeToDay: getTimeToDay,
- isObjectEmpty: isObjectEmpty,
- isWithinTimeRange: isWithinTimeRange,
- formatToHHMM: formatToHHMM,
- hideProvinceAndCity: hideProvinceAndCity,
- formatTimeScan: formatTimeScan,
- calculateRemainingTime: calculateRemainingTime,
- countToDay: countToDay,
- getFormattedTime: getFormattedTime,
- callPhone: callPhone,
- timestampToDays: timestampToDays,
- formatTimeDifference: formatTimeDifference
- };
|