tools.js
3.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*
* @Date: 2022-04-18 15:59:42
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2026-01-13 11:39:03
* @FilePath: /xyxBooking-weapp/src/utils/tools.js
* @Description: 文件描述
*/
import dayjs from 'dayjs';
import Taro from '@tarojs/taro';
// 格式化时间
const formatDate = (date) => {
return dayjs(date).format('YYYY-MM-DD HH:mm');
};
/**
* @description 判断设备信息
* @returns
*/
const wxInfo = () => {
const info = Taro.getSystemInfoSync();
const isAndroid = info.platform === 'android';
const isiOS = info.platform === 'ios';
// 简单模拟
return {
isAndroid,
isiOS,
isTable: false // 小程序通常不是 tablet 模式,或者可以根据 screenWidth 判断
};
};
/**
* @description 解析URL参数
* @param {*} url
* @returns
*/
const parseQueryString = url => {
if (!url) return {};
var json = {};
var arr = url.indexOf('?') >= 0 ? url.substr(url.indexOf('?') + 1).split('&') : [];
arr.forEach(item => {
var tmp = item.split('=');
json[tmp[0]] = tmp[1];
});
return json;
}
/**
* 字符串包含字符数组中字符的状态
* @param {*} array 字符数组
* @param {*} str 字符串
* @returns 包含状态
*/
const strExist = (array, str) => {
if (!str) return false;
const exist = array.filter(arr => {
if (str.indexOf(arr) >= 0) return str;
})
return exist.length > 0
}
/**
* 格式化日期时间字符串,提取开始/结束时间并拼接为「日期 开始时间-结束时间」格式
* @description 处理包含 begin_time/end_time 的数据对象,截取时间戳最后6位(毫秒/时区等冗余部分),
* 最终拼接为 "YYYY-MM-DD HH:mm:ss-HH:mm:ss" 格式的字符串
* @param {Object} data - 包含开始/结束时间的数据源对象
* @param {string} [data.begin_time] - 开始时间字符串(格式示例:2026-01-13T12:30:45.123456+08:00)
* @param {string} [data.end_time] - 结束时间字符串(格式同 begin_time)
* @returns {string} 格式化后的日期时间字符串,格式为「日期 开始时间-结束时间」;若入参无效返回空字符串
* @example
* 输入示例
* const timeData = {
* begin_time: '2026-01-13T10:00:00.987654+08:00',
* end_time: '2026-01-13T18:30:00.123456+08:00'
* };
* 调用函数
* formatDatetime(timeData); // 返回 "2026-01-13 10:00:00-18:30:00"
*
* @example
* 入参为空的情况
* formatDatetime(null); // 返回 ""
* formatDatetime({}); // 返回 ""
*
* @note 1. 入参时间字符串需保证前19位为有效格式(YYYY-MM-DDTHH:mm:ss),否则截取后可能出现异常;
* 2. 若 begin_time/end_time 缺失,拼接后可能出现 "undefined-undefined" 等异常,需保证入参完整性;
* 3. 该函数默认截取时间字符串前19位(slice(0, -6)),需根据实际时间格式调整截取长度
*/
const formatDatetime = (data) => {
// 格式化日期
if (!data) return '';
// 截取时间字符串最后6位(去除毫秒/时区等冗余部分)
const begin_time = data?.begin_time?.slice(0, -6) || '';
const end_time = data?.end_time?.slice(0, -6) || '';
// 拆分时间片段并拼接目标格式:日期 开始时间-结束时间
const [date, beginTime] = begin_time.split('T');
const [, endTime] = end_time.split('T');
// 兼容时间拆分失败的情况,避免返回 NaN/-undefined 等异常
if (!date || !beginTime || !endTime) return '';
return `${date} ${beginTime}-${endTime}`;
};
export { formatDate, wxInfo, parseQueryString, strExist, formatDatetime };