common.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  1. package utils
  2. import (
  3. "bufio"
  4. "crypto/cipher"
  5. "crypto/des"
  6. "crypto/hmac"
  7. "crypto/md5"
  8. "crypto/sha1"
  9. "crypto/sha256"
  10. "encoding/base64"
  11. "encoding/hex"
  12. "encoding/json"
  13. "errors"
  14. "fmt"
  15. "image"
  16. "image/png"
  17. "io"
  18. "math"
  19. "math/rand"
  20. "net"
  21. "net/http"
  22. "os"
  23. "os/exec"
  24. "path"
  25. "regexp"
  26. "sort"
  27. "strconv"
  28. "strings"
  29. "time"
  30. "github.com/shopspring/decimal"
  31. )
  32. // 随机数种子
  33. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  34. func GetRandString(size int) string {
  35. allLetterDigit := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "!", "@", "#", "$", "%", "^", "&", "*"}
  36. randomSb := ""
  37. digitSize := len(allLetterDigit)
  38. for i := 0; i < size; i++ {
  39. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  40. }
  41. return randomSb
  42. }
  43. func GetRandStringNoSpecialChar(size int) string {
  44. allLetterDigit := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
  45. randomSb := ""
  46. digitSize := len(allLetterDigit)
  47. for i := 0; i < size; i++ {
  48. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  49. }
  50. return randomSb
  51. }
  52. func StringsToJSON(str string) string {
  53. rs := []rune(str)
  54. jsons := ""
  55. for _, r := range rs {
  56. rint := int(r)
  57. if rint < 128 {
  58. jsons += string(r)
  59. } else {
  60. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  61. }
  62. }
  63. return jsons
  64. }
  65. // 序列化
  66. func ToString(v interface{}) string {
  67. data, _ := json.Marshal(v)
  68. return string(data)
  69. }
  70. // md5加密
  71. func MD5(data string) string {
  72. m := md5.Sum([]byte(data))
  73. return hex.EncodeToString(m[:])
  74. }
  75. // 获取数字随机字符
  76. func GetRandDigit(n int) string {
  77. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  78. }
  79. // 获取随机数
  80. func GetRandNumber(n int) int {
  81. return rnd.Intn(n)
  82. }
  83. func GetRandInt(min, max int) int {
  84. if min >= max || min == 0 || max == 0 {
  85. return max
  86. }
  87. return rand.Intn(max-min) + min
  88. }
  89. func GetToday(format string) string {
  90. today := time.Now().Format(format)
  91. return today
  92. }
  93. // 获取今天剩余秒数
  94. func GetTodayLastSecond() time.Duration {
  95. today := GetToday(FormatDate) + " 23:59:59"
  96. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  97. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  98. }
  99. // 处理出生日期函数
  100. func GetBrithDate(idcard string) string {
  101. l := len(idcard)
  102. var s string
  103. if l == 15 {
  104. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  105. return s
  106. }
  107. if l == 18 {
  108. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  109. return s
  110. }
  111. return GetToday(FormatDate)
  112. }
  113. // 处理性别
  114. func WhichSexByIdcard(idcard string) string {
  115. var sexs = [2]string{"女", "男"}
  116. length := len(idcard)
  117. if length == 18 {
  118. sex, _ := strconv.Atoi(string(idcard[16]))
  119. return sexs[sex%2]
  120. } else if length == 15 {
  121. sex, _ := strconv.Atoi(string(idcard[14]))
  122. return sexs[sex%2]
  123. }
  124. return "男"
  125. }
  126. // 截取小数点后几位
  127. func SubFloatToString(f float64, m int) string {
  128. n := strconv.FormatFloat(f, 'f', -1, 64)
  129. if n == "" {
  130. return ""
  131. }
  132. if m >= len(n) {
  133. return n
  134. }
  135. newn := strings.Split(n, ".")
  136. if m == 0 {
  137. return newn[0]
  138. }
  139. if len(newn) < 2 || m >= len(newn[1]) {
  140. return n
  141. }
  142. return newn[0] + "." + newn[1][:m]
  143. }
  144. // 截取小数点后几位
  145. func SubFloatToFloat(f float64, m int) float64 {
  146. newn := SubFloatToString(f, m)
  147. newf, _ := strconv.ParseFloat(newn, 64)
  148. return newf
  149. }
  150. // 截取小数点后几位
  151. func SubFloatToFloatStr(f float64, m int) string {
  152. newn := SubFloatToString(f, m)
  153. return newn
  154. }
  155. // 获取相差时间-年
  156. func GetYearDiffer(start_time, end_time string) int {
  157. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  158. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  159. age := t2.Year() - t1.Year()
  160. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  161. age--
  162. }
  163. return age
  164. }
  165. // 获取相差时间-秒
  166. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  167. diff := end_time.Unix() - start_time.Unix()
  168. return diff
  169. }
  170. func FixFloat(f float64, m int) float64 {
  171. newn := SubFloatToString(f+0.00000001, m)
  172. newf, _ := strconv.ParseFloat(newn, 64)
  173. return newf
  174. }
  175. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  176. func StrListToString(strList []string) (str string) {
  177. if len(strList) > 0 {
  178. for k, v := range strList {
  179. if k == 0 {
  180. str = v
  181. } else {
  182. str = str + "," + v
  183. }
  184. }
  185. return
  186. }
  187. return ""
  188. }
  189. // 数据没有记录
  190. func ErrNoRow() string {
  191. return "<QuerySeter> no row found"
  192. }
  193. // 校验邮箱格式
  194. func ValidateEmailFormatat(email string) bool {
  195. reg := regexp.MustCompile(RegularEmail)
  196. return reg.MatchString(email)
  197. }
  198. // 验证是否是手机号
  199. func ValidateMobileFormatat(mobileNum string) bool {
  200. reg := regexp.MustCompile(RegularMobile)
  201. return reg.MatchString(mobileNum)
  202. }
  203. // 判断文件是否存在
  204. func FileIsExist(filePath string) bool {
  205. _, err := os.Stat(filePath)
  206. return err == nil || os.IsExist(err)
  207. }
  208. // 获取图片扩展名
  209. func GetImgExt(file string) (ext string, err error) {
  210. var headerByte []byte
  211. headerByte = make([]byte, 8)
  212. fd, err := os.Open(file)
  213. if err != nil {
  214. return "", err
  215. }
  216. defer fd.Close()
  217. _, err = fd.Read(headerByte)
  218. if err != nil {
  219. return "", err
  220. }
  221. xStr := fmt.Sprintf("%x", headerByte)
  222. switch {
  223. case xStr == "89504e470d0a1a0a":
  224. ext = ".png"
  225. case xStr == "0000010001002020":
  226. ext = ".ico"
  227. case xStr == "0000020001002020":
  228. ext = ".cur"
  229. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  230. ext = ".gif"
  231. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  232. ext = ".tga"
  233. case xStr[:8] == "464f524d":
  234. ext = ".iff"
  235. case xStr[:8] == "52494646":
  236. ext = ".ani"
  237. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  238. ext = ".tiff"
  239. case xStr[:4] == "424d":
  240. ext = ".bmp"
  241. case xStr[:4] == "ffd8":
  242. ext = ".jpg"
  243. case xStr[:2] == "0a":
  244. ext = ".pcx"
  245. default:
  246. ext = ""
  247. }
  248. return ext, nil
  249. }
  250. // 保存图片
  251. func SaveImage(path string, img image.Image) (err error) {
  252. //需要保持的文件
  253. imgfile, err := os.Create(path)
  254. defer imgfile.Close()
  255. // 以PNG格式保存文件
  256. err = png.Encode(imgfile, img)
  257. return err
  258. }
  259. // 下载图片
  260. func DownloadImage(imgUrl string) (filePath string, err error) {
  261. imgPath := "./static/imgs/"
  262. fileName := path.Base(imgUrl)
  263. res, err := http.Get(imgUrl)
  264. if err != nil {
  265. fmt.Println("A error occurred!")
  266. return
  267. }
  268. defer res.Body.Close()
  269. // 获得get请求响应的reader对象
  270. reader := bufio.NewReaderSize(res.Body, 32*1024)
  271. filePath = imgPath + fileName
  272. file, err := os.Create(filePath)
  273. if err != nil {
  274. return
  275. }
  276. // 获得文件的writer对象
  277. writer := bufio.NewWriter(file)
  278. written, _ := io.Copy(writer, reader)
  279. fmt.Printf("Total length: %d \n", written)
  280. return
  281. }
  282. // 保存base64数据为文件
  283. func SaveBase64ToFile(content, path string) error {
  284. data, err := base64.StdEncoding.DecodeString(content)
  285. if err != nil {
  286. return err
  287. }
  288. f, err := os.Create(path)
  289. defer f.Close()
  290. if err != nil {
  291. return err
  292. }
  293. f.Write(data)
  294. return nil
  295. }
  296. func SaveBase64ToFileBySeek(content, path string) (err error) {
  297. data, err := base64.StdEncoding.DecodeString(content)
  298. exist, err := PathExists(path)
  299. if err != nil {
  300. return
  301. }
  302. if !exist {
  303. f, err := os.Create(path)
  304. if err != nil {
  305. return err
  306. }
  307. n, _ := f.Seek(0, 2)
  308. // 从末尾的偏移量开始写入内容
  309. _, err = f.WriteAt([]byte(data), n)
  310. defer f.Close()
  311. } else {
  312. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  313. if err != nil {
  314. return err
  315. }
  316. n, _ := f.Seek(0, 2)
  317. // 从末尾的偏移量开始写入内容
  318. _, err = f.WriteAt([]byte(data), n)
  319. defer f.Close()
  320. }
  321. return nil
  322. }
  323. func PathExists(path string) (bool, error) {
  324. _, err := os.Stat(path)
  325. if err == nil {
  326. return true, nil
  327. }
  328. if os.IsNotExist(err) {
  329. return false, nil
  330. }
  331. return false, err
  332. }
  333. func StartIndex(page, pagesize int) int {
  334. if page > 1 {
  335. return (page - 1) * pagesize
  336. }
  337. return 0
  338. }
  339. func PageCount(count, pagesize int) int {
  340. if count%pagesize > 0 {
  341. return count/pagesize + 1
  342. } else {
  343. return count / pagesize
  344. }
  345. }
  346. func TrimHtml(src string) string {
  347. //将HTML标签全转换成小写
  348. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  349. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  350. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  351. src = re.ReplaceAllString(src, "[图片]")
  352. re, _ = regexp.Compile("class[\\S\\s]+?>")
  353. src = re.ReplaceAllString(src, "")
  354. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  355. src = re.ReplaceAllString(src, "")
  356. return strings.TrimSpace(src)
  357. }
  358. //1556164246 -> 2019-04-25 03:50:46 +0000
  359. //timestamp
  360. func TimeToTimestamp() {
  361. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  362. }
  363. func ToUnicode(text string) string {
  364. textQuoted := strconv.QuoteToASCII(text)
  365. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  366. return textUnquoted
  367. }
  368. func VersionToInt(version string) int {
  369. version = strings.Replace(version, ".", "", -1)
  370. n, _ := strconv.Atoi(version)
  371. return n
  372. }
  373. func IsCheckInList(list []int, s int) bool {
  374. for _, v := range list {
  375. if v == s {
  376. return true
  377. }
  378. }
  379. return false
  380. }
  381. func round(num float64) int {
  382. return int(num + math.Copysign(0.5, num))
  383. }
  384. func toFixed(num float64, precision int) float64 {
  385. output := math.Pow(10, float64(precision))
  386. return float64(round(num*output)) / output
  387. }
  388. // GetWilsonScore returns Wilson Score
  389. func GetWilsonScore(p, n float64) float64 {
  390. if p == 0 && n == 0 {
  391. return 0
  392. }
  393. return toFixed(((p+1.9208)/(p+n)-1.96*math.Sqrt(p*n/(p+n)+0.9604)/(p+n))/(1+3.8416/(p+n)), 2)
  394. }
  395. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  396. func ChangeWordsToNum(str string) (numStr string) {
  397. words := ([]rune)(str)
  398. num := 0
  399. n := 0
  400. for i := 0; i < len(words); i++ {
  401. word := string(words[i : i+1])
  402. switch word {
  403. case "万":
  404. if n == 0 {
  405. n = 1
  406. }
  407. n = n * 10000
  408. num = num*10000 + n
  409. n = 0
  410. case "千":
  411. if n == 0 {
  412. n = 1
  413. }
  414. n = n * 1000
  415. num += n
  416. n = 0
  417. case "百":
  418. if n == 0 {
  419. n = 1
  420. }
  421. n = n * 100
  422. num += n
  423. n = 0
  424. case "十":
  425. if n == 0 {
  426. n = 1
  427. }
  428. n = n * 10
  429. num += n
  430. n = 0
  431. case "一":
  432. n += 1
  433. case "二":
  434. n += 2
  435. case "三":
  436. n += 3
  437. case "四":
  438. n += 4
  439. case "五":
  440. n += 5
  441. case "六":
  442. n += 6
  443. case "七":
  444. n += 7
  445. case "八":
  446. n += 8
  447. case "九":
  448. n += 9
  449. case "零":
  450. default:
  451. if n > 0 {
  452. num += n
  453. n = 0
  454. }
  455. if num == 0 {
  456. numStr += word
  457. } else {
  458. numStr += strconv.Itoa(num) + word
  459. num = 0
  460. }
  461. }
  462. }
  463. if n > 0 {
  464. num += n
  465. n = 0
  466. }
  467. if num != 0 {
  468. numStr += strconv.Itoa(num)
  469. }
  470. return
  471. }
  472. func Sha1(data string) string {
  473. sha1 := sha1.New()
  474. sha1.Write([]byte(data))
  475. return hex.EncodeToString(sha1.Sum([]byte("")))
  476. }
  477. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  478. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  479. out, err := exec.Command("bash", "-c", cmd).Output()
  480. if err != nil {
  481. return
  482. }
  483. outTimes := string(out)
  484. fmt.Println("outTimes:", outTimes)
  485. if outTimes != "" {
  486. timeArr := strings.Split(outTimes, ":")
  487. h := timeArr[0]
  488. m := timeArr[1]
  489. s := timeArr[2]
  490. hInt, err := strconv.Atoi(h)
  491. if err != nil {
  492. return playSeconds, err
  493. }
  494. mInt, err := strconv.Atoi(m)
  495. if err != nil {
  496. return playSeconds, err
  497. }
  498. s = strings.Trim(s, " ")
  499. s = strings.Trim(s, "\n")
  500. sInt, err := strconv.ParseFloat(s, 64)
  501. if err != nil {
  502. return playSeconds, err
  503. }
  504. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  505. }
  506. return
  507. }
  508. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  509. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  510. tradeCode = strings.Trim(tradeCode, " ")
  511. tradeCodeInt, err := strconv.Atoi(tradeCode)
  512. if err != nil {
  513. return
  514. }
  515. tradeCodeInt = tradeCodeInt + 1
  516. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  517. return
  518. }
  519. // excel日期字段格式化 yyyy-mm-dd
  520. func ConvertToFormatDay(excelDaysString string) string {
  521. // 2006-01-02 距离 1900-01-01的天数
  522. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  523. curDiffDay := excelDaysString
  524. b, _ := strconv.Atoi(curDiffDay)
  525. // 获取excel的日期距离2006-01-02的天数
  526. realDiffDay := b - baseDiffDay
  527. //fmt.Println("realDiffDay:",realDiffDay)
  528. // 距离2006-01-02 秒数
  529. realDiffSecond := realDiffDay * 24 * 3600
  530. //fmt.Println("realDiffSecond:",realDiffSecond)
  531. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  532. baseOriginSecond := 1136185445
  533. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  534. return resultTime
  535. }
  536. func CheckPwd(pwd string) bool {
  537. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  538. reg := regexp.MustCompile(compile)
  539. flag := reg.MatchString(pwd)
  540. return flag
  541. }
  542. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  543. // 数字月份必须前置补零
  544. if len(myMonth) == 1 {
  545. myMonth = "0" + myMonth
  546. }
  547. yInt, _ := strconv.Atoi(myYear)
  548. timeLayout := "2006-01-02 15:04:05"
  549. loc, _ := time.LoadLocation("Local")
  550. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  551. newMonth := theTime.Month()
  552. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  553. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  554. return t1, t2
  555. }
  556. // 移除字符串中的空格
  557. func TrimStr(str string) (str2 string) {
  558. return strings.Replace(str, " ", "", -1)
  559. }
  560. // 字符串转换为time
  561. func StrTimeToTime(strTime string) time.Time {
  562. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  563. loc, _ := time.LoadLocation("Local") //重要:获取时区
  564. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  565. return resultTime
  566. }
  567. // GetOrmInReplace 获取orm的in查询替换?的方法
  568. func GetOrmInReplace(num int) string {
  569. template := make([]string, num)
  570. for i := 0; i < num; i++ {
  571. template[i] = "?"
  572. }
  573. return strings.Join(template, ",")
  574. }
  575. // RevSlice 反转切片
  576. func RevSlice(slice []int) []int {
  577. for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
  578. slice[i], slice[j] = slice[j], slice[i]
  579. }
  580. return slice
  581. }
  582. // GetTimeSubDay 计算两个时间的自然日期差
  583. func GetTimeSubDay(t1, t2 time.Time) int {
  584. var day int
  585. swap := false
  586. if t1.Unix() > t2.Unix() {
  587. t1, t2 = t2, t1
  588. swap = true
  589. }
  590. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  591. day = int(t2.Sub(t1).Hours() / 24)
  592. // 计算在t1+两个时间的余数之后天数是否有变化
  593. if t1_.Day() != t1.Day() {
  594. day += 1
  595. }
  596. if swap {
  597. day = -day
  598. }
  599. return day
  600. }
  601. // GetDaysBetween2Date 计算两个日期之间相差几天
  602. func GetDaysBetween2Date(format, date1Str, date2Str string) (int, error) {
  603. // 将字符串转化为Time格式
  604. date1, err := time.ParseInLocation(format, date1Str, time.Local)
  605. if err != nil {
  606. return 0, err
  607. }
  608. // 将字符串转化为Time格式
  609. date2, err := time.ParseInLocation(format, date2Str, time.Local)
  610. if err != nil {
  611. return 0, err
  612. }
  613. //计算相差天数
  614. return int(date1.Sub(date2).Hours() / 24), nil
  615. }
  616. // MapSorter 对于map 排序
  617. type MapSorter []Item
  618. type Item struct {
  619. Key int
  620. Val float64
  621. }
  622. func NewMapSorter(m map[int]float64) MapSorter {
  623. ms := make(MapSorter, 0, len(m))
  624. for k, v := range m {
  625. ms = append(ms, Item{k, v})
  626. }
  627. return ms
  628. }
  629. func (ms MapSorter) Len() int {
  630. return len(ms)
  631. }
  632. func (ms MapSorter) Less(i, j int) bool {
  633. return ms[i].Val > ms[j].Val // 按值排序
  634. //return ms[i].Key < ms[j].Key // 按键排序
  635. }
  636. func (ms MapSorter) Swap(i, j int) {
  637. ms[i], ms[j] = ms[j], ms[i]
  638. }
  639. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  640. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  641. for _, id := range idIntList {
  642. if id == searchId {
  643. has = true
  644. return
  645. }
  646. }
  647. return
  648. }
  649. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  650. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  651. for _, id := range idStrList {
  652. if id == searchId {
  653. has = true
  654. return
  655. }
  656. }
  657. return
  658. }
  659. // GetDateByDateType 通过dateType获取需要的开始/结束日期
  660. func GetDateByDateType(dateType int, tmpStartDate, tmpEndDate string) (startDate, endDate string) {
  661. startDate = tmpStartDate
  662. endDate = tmpEndDate
  663. switch dateType {
  664. case 1:
  665. startDate = "2000-01-01"
  666. endDate = ""
  667. case 2:
  668. startDate = "2010-01-01"
  669. endDate = ""
  670. case 3:
  671. startDate = "2015-01-01"
  672. endDate = ""
  673. case 4:
  674. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  675. startDate = "2021-01-01"
  676. endDate = ""
  677. case 5:
  678. //startDate = startDate + "-01"
  679. //endDate = endDate + "-01"
  680. case 6:
  681. //startDate = startDate + "-01"
  682. endDate = ""
  683. case 7:
  684. startDate = "2018-01-01"
  685. endDate = ""
  686. case 8:
  687. startDate = "2019-01-01"
  688. endDate = ""
  689. case 9:
  690. startDate = "2020-01-01"
  691. endDate = ""
  692. case 11:
  693. startDate = "2022-01-01"
  694. endDate = ""
  695. }
  696. // 兼容日期错误
  697. {
  698. if strings.Count(startDate, "-") == 1 {
  699. startDate = startDate + "-01"
  700. }
  701. if strings.Count(endDate, "-") == 1 {
  702. endDate = endDate + "-01"
  703. }
  704. }
  705. return
  706. }
  707. // GetDateByDateType2 通过dateType获取需要的开始/结束日期(日期类型:1:最近3月;2:最近6月;3:最近1年;4:最近2年;5:最近3年;6:最近5年;7:最近10年,8:自定义时间)
  708. func GetDateByDateType2(dateType int, currDate time.Time) (startDate time.Time) {
  709. switch dateType {
  710. case 1:
  711. startDate = currDate.AddDate(0, -3, 0)
  712. case 2:
  713. startDate = currDate.AddDate(0, -6, 0)
  714. case 3:
  715. startDate = currDate.AddDate(-1, 0, 0)
  716. case 4:
  717. startDate = currDate.AddDate(-2, 0, 0)
  718. case 5:
  719. startDate = currDate.AddDate(-3, 0, 0)
  720. case 6:
  721. startDate = currDate.AddDate(-5, 0, 0)
  722. case 7:
  723. startDate = currDate.AddDate(-10, 0, 0)
  724. }
  725. return
  726. }
  727. // GetCeilNewNum 保留n位有效数字的向上取整
  728. // @params num 实际数据
  729. // @params baseLen 需要保留的有效位数
  730. func GetCeilNewNum(num float64, baseLen int) (newNum float64) {
  731. if num >= 1 {
  732. tmpNum := int(math.Ceil(num)) // 向上取整
  733. str := strconv.Itoa(tmpNum)
  734. lenStr := len(str)
  735. if lenStr > baseLen {
  736. newNumStr := str[0:baseLen]
  737. newNumInt, _ := strconv.Atoi(newNumStr)
  738. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  739. if newNum < num {
  740. newNumInt += 1
  741. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  742. }
  743. } else {
  744. newNum = float64(tmpNum)
  745. }
  746. return
  747. } else if num > 0 {
  748. // 这是小数
  749. str := strconv.FormatFloat(num, 'f', -1, 64)
  750. // 去除小数点和负号
  751. str = removeDecimalPoint(str)
  752. // 计算字符串长度
  753. lenStr := len(str)
  754. if lenStr > baseLen {
  755. newNumStr := str[0:baseLen]
  756. newNumInt, _ := strconv.Atoi(newNumStr)
  757. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  758. if newNum < num {
  759. newNumInt += 1
  760. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  761. }
  762. } else {
  763. newNum = num
  764. }
  765. } else if num > -1 {
  766. // 这是小数
  767. str := strconv.FormatFloat(num, 'f', -1, 64)
  768. // 去除小数点和负号
  769. str = removeDecimalPoint(str)
  770. // 计算字符串长度
  771. lenStr := len(str)
  772. if lenStr > baseLen {
  773. newNumStr := str[0:baseLen]
  774. newNumInt, _ := strconv.Atoi(newNumStr)
  775. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  776. newNum = -newNum
  777. if newNum < num {
  778. newNumInt -= 1
  779. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  780. newNum = -newNum
  781. }
  782. } else {
  783. newNum = num
  784. }
  785. if newNum == -0 {
  786. newNum = 0
  787. }
  788. } else { // 小于等于-1
  789. tmpNumFloat := math.Abs(num)
  790. tmpNum := int(math.Floor(tmpNumFloat)) // 向上取整
  791. str := strconv.Itoa(tmpNum)
  792. lenStr := len(str)
  793. if lenStr > baseLen {
  794. newNumStr := str[0:baseLen]
  795. //fmt.Println("newNumStr:", newNumStr)
  796. newNumInt, _ := strconv.Atoi(newNumStr)
  797. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  798. newNum = -newNum
  799. if newNum < num {
  800. newNumInt -= 1
  801. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  802. newNum = -newNum
  803. }
  804. } else {
  805. newNum = float64(-tmpNum)
  806. }
  807. }
  808. return
  809. }
  810. // GetFloorNewNum 保留n位有效数字的向下取整
  811. // @params num 实际数据
  812. // @params baseLen 需要保留的有效位数
  813. func GetFloorNewNum(num float64, baseLen int) (newNum float64) {
  814. if num >= 1 {
  815. tmpNum := int(math.Floor(num)) // 向上取整
  816. str := strconv.Itoa(tmpNum)
  817. lenStr := len(str)
  818. if lenStr > baseLen {
  819. newNumStr := str[0:baseLen]
  820. newNumInt, _ := strconv.Atoi(newNumStr)
  821. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  822. if newNum < num {
  823. newNumInt -= 1
  824. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  825. }
  826. } else {
  827. newNum = float64(tmpNum)
  828. }
  829. return
  830. } else if num > 0 {
  831. // 这是小数
  832. str := strconv.FormatFloat(num, 'f', -1, 64)
  833. // 去除小数点和负号
  834. str = removeDecimalPoint(str)
  835. // 计算字符串长度
  836. lenStr := len(str)
  837. if lenStr > baseLen {
  838. newNumStr := str[0:baseLen]
  839. newNumInt, _ := strconv.Atoi(newNumStr)
  840. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  841. if newNum > num {
  842. newNumInt -= 1
  843. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  844. }
  845. } else {
  846. newNum = num
  847. }
  848. } else if num > -1 {
  849. // 这是小数
  850. str := strconv.FormatFloat(num, 'f', -1, 64)
  851. // 去除小数点和负号
  852. str = removeDecimalPoint(str)
  853. // 计算字符串长度
  854. lenStr := len(str)
  855. if lenStr > baseLen {
  856. newNumStr := str[0:baseLen]
  857. newNumInt, _ := strconv.Atoi(newNumStr)
  858. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  859. newNum = -newNum
  860. if newNum > num {
  861. newNumInt += 1
  862. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  863. newNum = -newNum
  864. }
  865. } else {
  866. newNum = num
  867. }
  868. if newNum == -0 {
  869. newNum = 0
  870. }
  871. } else { // 小于等于-1
  872. tmpNumFloat := math.Abs(num)
  873. tmpNum := int(math.Ceil(tmpNumFloat)) // 向上取整
  874. str := strconv.Itoa(tmpNum)
  875. lenStr := len(str)
  876. if lenStr > baseLen {
  877. newNumStr := str[0:baseLen]
  878. //fmt.Println("newNumStr:", newNumStr)
  879. newNumInt, _ := strconv.Atoi(newNumStr)
  880. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  881. newNum = -newNum
  882. if newNum > num {
  883. newNumInt += 1
  884. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  885. newNum = -newNum
  886. }
  887. } else {
  888. newNum = float64(-tmpNum)
  889. }
  890. }
  891. return
  892. }
  893. // 去除小数点和负号
  894. func removeDecimalPoint(str string) string {
  895. // 去除小数点
  896. str = str[strings.Index(str, ".")+1:]
  897. return str
  898. }
  899. func GetLocalIP() (ip string, err error) {
  900. addrs, err := net.InterfaceAddrs()
  901. if err != nil {
  902. return
  903. }
  904. for _, addr := range addrs {
  905. ipAddr, ok := addr.(*net.IPNet)
  906. if !ok {
  907. continue
  908. }
  909. if ipAddr.IP.IsLoopback() {
  910. continue
  911. }
  912. if !ipAddr.IP.IsGlobalUnicast() {
  913. continue
  914. }
  915. return ipAddr.IP.String(), nil
  916. }
  917. return
  918. }
  919. func GetDateByDateTypeV2(dateType int, tmpStartDate, tmpEndDate string, startYear int, latestDate time.Time) (startDate, endDate string) {
  920. startDate = tmpStartDate
  921. endDate = tmpEndDate
  922. switch dateType {
  923. case 1:
  924. startDate = "2000-01-01"
  925. endDate = ""
  926. case 2:
  927. startDate = "2010-01-01"
  928. endDate = ""
  929. case 3:
  930. startDate = "2015-01-01"
  931. endDate = ""
  932. case 4:
  933. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  934. startDate = "2021-01-01"
  935. endDate = ""
  936. case 5:
  937. //startDate = startDate + "-01"
  938. //endDate = endDate + "-01"
  939. case 6:
  940. //startDate = startDate + "-01"
  941. endDate = ""
  942. case 7:
  943. startDate = "2018-01-01"
  944. endDate = ""
  945. case 8:
  946. startDate = "2019-01-01"
  947. endDate = ""
  948. case 9:
  949. startDate = "2020-01-01"
  950. endDate = ""
  951. case 11:
  952. startDate = "2022-01-01"
  953. endDate = ""
  954. case 12:
  955. startDate = "2023-01-01"
  956. endDate = ""
  957. case 13:
  958. startDate = "2024-01-01"
  959. endDate = ""
  960. case DateTypeNYears:
  961. if startYear == 0 { //默认取最近5年
  962. startYear = 5
  963. }
  964. if latestDate.IsZero() {
  965. return
  966. }
  967. startDate = latestDate.AddDate(-startYear, 0, 0).Format(FormatDate)
  968. endDate = ""
  969. }
  970. // 兼容日期错误
  971. {
  972. if strings.Count(startDate, "-") == 1 {
  973. startDate = startDate + "-01"
  974. }
  975. if strings.Count(endDate, "-") == 1 {
  976. endTime, err := time.Parse(FormatYearMonthDate, endDate)
  977. if err != nil {
  978. return
  979. }
  980. endDate = endTime.AddDate(0, 1, -1).Format(FormatDate)
  981. }
  982. }
  983. return
  984. }
  985. func GetColorMap() map[int]string {
  986. colorMap := make(map[int]string)
  987. colors := []string{"#0000FF", "#FF0000", "#999999", "#000000", "#7CB5EC", "#90ED7D", "#F7A35C", "#8085E9",
  988. "#F15C80", "#E4D354", "#2B908F", "#F45B5B", "#91E8E1", "#FDA8C7", "#8A4294",
  989. "#578B5A", "#0033FF", "#849EC1", "#FFDF0C", "#005496", "#00F0FF", "#4D535B",
  990. "#4F4C34", "#804141", "#86BABD", "#8AA3FF", "#960000", "#A173DB", "#A39340",
  991. "#CE814A", "#D1D2E6", "#EAB7B7", "#FF2E7A", "#FF4AF8", "#FF785B", "#FF9696", "#FFA800", "#FFBC97", "#FFDFDF"}
  992. for k, v := range colors {
  993. colorMap[k] = v
  994. }
  995. return colorMap
  996. }
  997. // GetDaysDiff1900 计算日期距离1900-01-01的天数
  998. func GetDaysDiff1900(date string) int {
  999. // 将字符串转换为时间类型
  1000. //从1899年12月30日开始是因为Excel的日期计算是基于1900年1月1日的,而1900年并不是闰年,因此Excel日期计算存在一个错误。为了修正这个错误,
  1001. //我们将时间回溯到1899年12月30日,这样在进行日期计算时可以正确地处理Excel日期。
  1002. tStart, err := time.ParseInLocation(FormatDate, "1899-12-30", time.Local)
  1003. if err != nil {
  1004. return 0
  1005. }
  1006. tEnd, err := time.ParseInLocation(FormatDate, date, time.Local)
  1007. if err != nil {
  1008. return 0
  1009. }
  1010. // 计算两个日期之间的天数差值
  1011. duration := tEnd.Sub(tStart).Hours() / 24
  1012. days := int(duration)
  1013. return days
  1014. }
  1015. func ReplaceFormulaByTagMap(valTagMap map[string]int, formulaStr string) string {
  1016. funMap := getFormulaMap()
  1017. for k, v := range funMap {
  1018. formulaStr = strings.Replace(formulaStr, k, v, -1)
  1019. }
  1020. replaceCount := 0
  1021. for tag, val := range valTagMap {
  1022. dvStr := fmt.Sprintf("%v", val)
  1023. formulaStr = strings.Replace(formulaStr, tag, dvStr, -1)
  1024. replaceCount++
  1025. }
  1026. for k, v := range funMap {
  1027. formulaStr = strings.Replace(formulaStr, v, k, -1)
  1028. }
  1029. return formulaStr
  1030. }
  1031. // GetFrequencyEn 获取频度的英文版
  1032. func GetFrequencyEn(frequency string) (frequencyEn string) {
  1033. switch frequency {
  1034. case "日度":
  1035. frequencyEn = "day"
  1036. return
  1037. case "周度":
  1038. frequencyEn = "week"
  1039. return
  1040. case "旬度":
  1041. frequencyEn = "ten days"
  1042. return
  1043. case "月度":
  1044. frequencyEn = "month"
  1045. return
  1046. case "季度":
  1047. frequencyEn = "quarter"
  1048. return
  1049. case "年度":
  1050. frequencyEn = "year"
  1051. return
  1052. }
  1053. return
  1054. }
  1055. // DateConvMysqlConvMongo
  1056. // @Description: 将mysql中的日期比较符转换成mongo中的日期比较符
  1057. // @author: Roc
  1058. // @datetime 2024-05-08 11:03:26
  1059. // @param dateCon string
  1060. func DateConvMysqlConvMongo(dateCon string) string {
  1061. cond := ""
  1062. switch dateCon {
  1063. case "=":
  1064. cond = "$eq"
  1065. case "<":
  1066. cond = "$lt"
  1067. case "<=":
  1068. cond = "$lte"
  1069. case ">":
  1070. cond = "$gt"
  1071. case ">=":
  1072. cond = "$gte"
  1073. }
  1074. return cond
  1075. }
  1076. // HmacSha256 计算HmacSha256
  1077. // key 是加密所使用的key
  1078. // data 是加密的内容
  1079. func HmacSha256(key string, data string) []byte {
  1080. mac := hmac.New(sha256.New, []byte(key))
  1081. _, _ = mac.Write([]byte(data))
  1082. return mac.Sum(nil)
  1083. }
  1084. // HmacSha256ToBase64 将加密后的二进制转Base64字符串
  1085. func HmacSha256ToBase64(key string, data string) string {
  1086. return base64.URLEncoding.EncodeToString(HmacSha256(key, data))
  1087. }
  1088. func GetSign(nonce, timestamp, appId, secret string) (sign string) {
  1089. signStrMap := map[string]string{
  1090. "nonce": nonce,
  1091. "timestamp": timestamp,
  1092. "appid": appId,
  1093. }
  1094. keys := make([]string, 0, len(signStrMap))
  1095. for k := range signStrMap {
  1096. keys = append(keys, k)
  1097. }
  1098. sort.Strings(keys)
  1099. var signStr string
  1100. for _, k := range keys {
  1101. signStr += k + "=" + signStrMap[k] + "&"
  1102. }
  1103. signStr = strings.Trim(signStr, "&")
  1104. fmt.Println("signStr:" + signStr)
  1105. sign = HmacSha256ToBase64(secret, signStr)
  1106. return
  1107. }
  1108. func TimeTransferString(format string, t time.Time) string {
  1109. str := t.Format(format)
  1110. if t.IsZero() {
  1111. return ""
  1112. }
  1113. return str
  1114. }
  1115. func DesBase64Decrypt(crypted []byte, desKey string) []byte {
  1116. result, _ := base64.StdEncoding.DecodeString(string(crypted))
  1117. remain := len(result) % 8
  1118. if remain > 0 {
  1119. mod := 8 - remain
  1120. for i := 0; i < mod; i++ {
  1121. result = append(result, 0)
  1122. }
  1123. }
  1124. origData, err := TripleDesDecrypt(result, []byte(desKey))
  1125. if err != nil {
  1126. panic(any(err))
  1127. }
  1128. return origData
  1129. }
  1130. // // 3DES解密
  1131. func TripleDesDecrypt(crypted, key []byte) ([]byte, error) {
  1132. block, err := des.NewTripleDESCipher(key)
  1133. if err != nil {
  1134. return nil, err
  1135. }
  1136. blockMode := cipher.NewCBCDecrypter(block, key[:8])
  1137. origData := make([]byte, len(crypted))
  1138. // origData := crypted
  1139. blockMode.CryptBlocks(origData, crypted)
  1140. origData = PKCS5UnPadding(origData)
  1141. // origData = ZeroUnPadding(origData)
  1142. return origData, nil
  1143. }
  1144. func PKCS5UnPadding(origData []byte) []byte {
  1145. length := len(origData)
  1146. // 去掉最后一个字节 unpadding 次
  1147. unpadding := int(origData[length-1])
  1148. return origData[:(length - unpadding)]
  1149. }
  1150. // handleSystemAppointDateT
  1151. // @Description: 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  1152. // @author: Roc
  1153. // @datetime2023-10-27 09:31:35
  1154. // @param Frequency string
  1155. // @param Day string
  1156. // @return date string
  1157. // @return err error
  1158. // @return errMsg string
  1159. func HandleSystemAppointDateT(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
  1160. //currDate := time.Now()
  1161. switch frequency {
  1162. case "本周":
  1163. day := int(currDate.Weekday())
  1164. if day == 0 { // 周日
  1165. day = 7
  1166. }
  1167. num := 0
  1168. switch appointDay {
  1169. case "周一":
  1170. num = 1
  1171. case "周二":
  1172. num = 2
  1173. case "周三":
  1174. num = 3
  1175. case "周四":
  1176. num = 4
  1177. case "周五":
  1178. num = 5
  1179. case "周六":
  1180. num = 6
  1181. case "周日":
  1182. num = 7
  1183. }
  1184. day = num - day
  1185. date = currDate.AddDate(0, 0, day).Format(FormatDate)
  1186. case "本旬":
  1187. day := currDate.Day()
  1188. var tmpDate time.Time
  1189. switch appointDay {
  1190. case "第一天":
  1191. if day <= 10 {
  1192. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1193. } else if day <= 20 {
  1194. tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
  1195. } else {
  1196. tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
  1197. }
  1198. case "最后一天":
  1199. if day <= 10 {
  1200. tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
  1201. } else if day <= 20 {
  1202. tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
  1203. } else {
  1204. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1205. }
  1206. }
  1207. date = tmpDate.Format(FormatDate)
  1208. case "本月":
  1209. var tmpDate time.Time
  1210. switch appointDay {
  1211. case "第一天":
  1212. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1213. case "最后一天":
  1214. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1215. }
  1216. date = tmpDate.Format(FormatDate)
  1217. case "本季":
  1218. month := currDate.Month()
  1219. var tmpDate time.Time
  1220. switch appointDay {
  1221. case "第一天":
  1222. if month <= 3 {
  1223. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1224. } else if month <= 6 {
  1225. tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
  1226. } else if month <= 9 {
  1227. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1228. } else {
  1229. tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
  1230. }
  1231. case "最后一天":
  1232. if month <= 3 {
  1233. tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
  1234. } else if month <= 6 {
  1235. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1236. } else if month <= 9 {
  1237. tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
  1238. } else {
  1239. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1240. }
  1241. }
  1242. date = tmpDate.Format(FormatDate)
  1243. case "本半年":
  1244. month := currDate.Month()
  1245. var tmpDate time.Time
  1246. switch appointDay {
  1247. case "第一天":
  1248. if month <= 6 {
  1249. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1250. } else {
  1251. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1252. }
  1253. case "最后一天":
  1254. if month <= 6 {
  1255. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1256. } else {
  1257. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1258. }
  1259. }
  1260. date = tmpDate.Format(FormatDate)
  1261. case "本年":
  1262. var tmpDate time.Time
  1263. switch appointDay {
  1264. case "第一天":
  1265. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1266. case "最后一天":
  1267. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1268. }
  1269. date = tmpDate.Format(FormatDate)
  1270. default:
  1271. errMsg = "错误的日期频度:" + frequency
  1272. err = errors.New(errMsg)
  1273. return
  1274. }
  1275. return
  1276. }
  1277. func CompareFloatByOpStrings(op string, a, b float64) bool {
  1278. switch op {
  1279. case "=":
  1280. return a == b
  1281. case ">":
  1282. return a > b
  1283. case ">=":
  1284. return a >= b
  1285. case "<=":
  1286. return a <= b
  1287. case "<":
  1288. return a < b
  1289. }
  1290. return false
  1291. }
  1292. // RoundNumber 保留小数位数
  1293. func RoundNumber(num string, decimalPlaces int, hasPercent bool) string {
  1294. numDecimal, _ := decimal.NewFromString(num)
  1295. if hasPercent {
  1296. numDecimal = numDecimal.Mul(decimal.NewFromInt(100))
  1297. }
  1298. numStr := numDecimal.Round(int32(decimalPlaces)).StringFixed(int32(decimalPlaces))
  1299. if hasPercent {
  1300. numStr += "%"
  1301. }
  1302. return numStr
  1303. }