helper.js
2.71 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
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
* @Author: limin
* @Date: 2019-11-21 11:19:43
* @Last Modified by: limin
* @Last Modified time: 2020-01-08 13:51:53
*/
const moment = require("moment");
const constant = require("../common/constant");
exports.moment = moment;
/*
* string.replace_all()---字符替换所有指定字符
* @parameter: from--原文本要替换值
* @parameter: to--将要替换值
*/
String.prototype.replace_all = function (from, to) {
var regExp = new RegExp(from, "g");
return this.replace(regExp, to);
}
// exports.relativeTime = time => moment(new Date(time * 1000)).fromNow();
exports.date = (n, f = "YYYY-MM-DD") => moment().add(n, "days").format(f);
exports.format_date = (date, f = "YYYY-MM-DD") =>moment(date+'').format(f);
/**
* 结束日期格式化函数
*/
exports.format_end_date = end => `${end} 23:59:59`;
/**
* 字符串转json 如果是json字符串 返回json对象 如果不是JSON字符串 返回原始字符串
*/
exports.json_parser = str => {
var res;
try {
res = JSON.parse(str);
} catch (error) {
res = str;
}
return res;
};
/**
* json对象转字符串
*/
exports.json_stringify = obj => {
var res;
if (typeof obj === "string") {
return obj;
}
try {
res = JSON.stringify(obj);
} catch (error) {
res = obj;
}
return res;
};
/**
*
*/
exports.percent = (num, total, fixed = 2) =>
(Math.round(num / total * 10000) / 100.00 + "%");
// (~~((~~num / ~~total) * 100).toFixed(fixed)) + "%";
/**
* 简单封装 sequelize 查询参数
*/
// exports.seq_option = function({
// pid,
// cid,
// n,
// limit,
// order,
// day,
// beginDate,
// endDate
// }) {
// let where = {};
// const { between } = this.ctx.app.Sequelize.Op;
// if (cid) {
// where.city_code = cid;
// } else if (pid) {
// where.prov_code = pid;
// }
// if (day) {
// //如果有具体天数 就直接查询具体一天的数据(优先具体哪一天)
// where.day = day;
// } else if (n) {
// // 查询近N天的数据 不包括今天
// where.day = {
// [between]: [this.date(n), this.format_end_date(this.date(-1))]
// };
// } else if (n === 0) {
// // 查询
// where.day = {
// [between]: [this.date(0), this.format_end_date(this.date(0))]
// };
// } else if (beginDate) {
// if (!endDate) {
// endDate = beginDate;
// }
// if (!endDate.includes(":")) {
// endDate = this.format_end_date(endDate);
// }
// where.day = {
// [between]: [beginDate, endDate]
// };
// }
// const option = {
// where,
// raw: true
// };
// if (limit) {
// option.limit = +limit;
// }
// if (order) {
// option.order = order;
// }
// return option;
// };
exports.constant = constant;