common.go 36 KB

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