common.go 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504
  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. return "?"
  586. }
  587. // RevSlice 反转切片
  588. func RevSlice(slice []int) []int {
  589. for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
  590. slice[i], slice[j] = slice[j], slice[i]
  591. }
  592. return slice
  593. }
  594. // GetTimeSubDay 计算两个时间的自然日期差
  595. func GetTimeSubDay(t1, t2 time.Time) int {
  596. var day int
  597. swap := false
  598. if t1.Unix() > t2.Unix() {
  599. t1, t2 = t2, t1
  600. swap = true
  601. }
  602. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  603. day = int(t2.Sub(t1).Hours() / 24)
  604. // 计算在t1+两个时间的余数之后天数是否有变化
  605. if t1_.Day() != t1.Day() {
  606. day += 1
  607. }
  608. if swap {
  609. day = -day
  610. }
  611. return day
  612. }
  613. // GetDaysBetween2Date 计算两个日期之间相差几天
  614. func GetDaysBetween2Date(format, date1Str, date2Str string) (int, error) {
  615. // 将字符串转化为Time格式
  616. date1, err := time.ParseInLocation(format, date1Str, time.Local)
  617. if err != nil {
  618. return 0, err
  619. }
  620. // 将字符串转化为Time格式
  621. date2, err := time.ParseInLocation(format, date2Str, time.Local)
  622. if err != nil {
  623. return 0, err
  624. }
  625. //计算相差天数
  626. return int(date1.Sub(date2).Hours() / 24), nil
  627. }
  628. // MapSorter 对于map 排序
  629. type MapSorter []Item
  630. type Item struct {
  631. Key int
  632. Val float64
  633. }
  634. func NewMapSorter(m map[int]float64) MapSorter {
  635. ms := make(MapSorter, 0, len(m))
  636. for k, v := range m {
  637. ms = append(ms, Item{k, v})
  638. }
  639. return ms
  640. }
  641. func (ms MapSorter) Len() int {
  642. return len(ms)
  643. }
  644. func (ms MapSorter) Less(i, j int) bool {
  645. return ms[i].Val > ms[j].Val // 按值排序
  646. //return ms[i].Key < ms[j].Key // 按键排序
  647. }
  648. func (ms MapSorter) Swap(i, j int) {
  649. ms[i], ms[j] = ms[j], ms[i]
  650. }
  651. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  652. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  653. for _, id := range idIntList {
  654. if id == searchId {
  655. has = true
  656. return
  657. }
  658. }
  659. return
  660. }
  661. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  662. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  663. for _, id := range idStrList {
  664. if id == searchId {
  665. has = true
  666. return
  667. }
  668. }
  669. return
  670. }
  671. // GetDateByDateType 通过dateType获取需要的开始/结束日期
  672. func GetDateByDateType(dateType int, tmpStartDate, tmpEndDate string) (startDate, endDate string) {
  673. startDate = tmpStartDate
  674. endDate = tmpEndDate
  675. switch dateType {
  676. case 1:
  677. startDate = "2000-01-01"
  678. endDate = ""
  679. case 2:
  680. startDate = "2010-01-01"
  681. endDate = ""
  682. case 3:
  683. startDate = "2015-01-01"
  684. endDate = ""
  685. case 4:
  686. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  687. startDate = "2021-01-01"
  688. endDate = ""
  689. case 5:
  690. //startDate = startDate + "-01"
  691. //endDate = endDate + "-01"
  692. case 6:
  693. //startDate = startDate + "-01"
  694. endDate = ""
  695. case 7:
  696. startDate = "2018-01-01"
  697. endDate = ""
  698. case 8:
  699. startDate = "2019-01-01"
  700. endDate = ""
  701. case 9:
  702. startDate = "2020-01-01"
  703. endDate = ""
  704. case 11:
  705. startDate = "2022-01-01"
  706. endDate = ""
  707. }
  708. // 兼容日期错误
  709. {
  710. if strings.Count(startDate, "-") == 1 {
  711. startDate = startDate + "-01"
  712. }
  713. if strings.Count(endDate, "-") == 1 {
  714. endDate = endDate + "-01"
  715. }
  716. }
  717. return
  718. }
  719. // GetDateByDateType2 通过dateType获取需要的开始/结束日期(日期类型:1:最近3月;2:最近6月;3:最近1年;4:最近2年;5:最近3年;6:最近5年;7:最近10年,8:自定义时间)
  720. func GetDateByDateType2(dateType int, currDate time.Time) (startDate time.Time) {
  721. switch dateType {
  722. case 1:
  723. startDate = currDate.AddDate(0, -3, 0)
  724. case 2:
  725. startDate = currDate.AddDate(0, -6, 0)
  726. case 3:
  727. startDate = currDate.AddDate(-1, 0, 0)
  728. case 4:
  729. startDate = currDate.AddDate(-2, 0, 0)
  730. case 5:
  731. startDate = currDate.AddDate(-3, 0, 0)
  732. case 6:
  733. startDate = currDate.AddDate(-5, 0, 0)
  734. case 7:
  735. startDate = currDate.AddDate(-10, 0, 0)
  736. }
  737. return
  738. }
  739. // GetCeilNewNum 保留n位有效数字的向上取整
  740. // @params num 实际数据
  741. // @params baseLen 需要保留的有效位数
  742. func GetCeilNewNum(num float64, baseLen int) (newNum float64) {
  743. if num >= 1 {
  744. tmpNum := int(math.Ceil(num)) // 向上取整
  745. str := strconv.Itoa(tmpNum)
  746. lenStr := len(str)
  747. if lenStr > baseLen {
  748. newNumStr := str[0:baseLen]
  749. newNumInt, _ := strconv.Atoi(newNumStr)
  750. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  751. if newNum < num {
  752. newNumInt += 1
  753. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  754. }
  755. } else {
  756. newNum = float64(tmpNum)
  757. }
  758. return
  759. } else if num > 0 {
  760. // 这是小数
  761. str := strconv.FormatFloat(num, 'f', -1, 64)
  762. // 去除小数点和负号
  763. str = removeDecimalPoint(str)
  764. // 计算字符串长度
  765. lenStr := len(str)
  766. if lenStr > baseLen {
  767. newNumStr := str[0:baseLen]
  768. newNumInt, _ := strconv.Atoi(newNumStr)
  769. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  770. if newNum < num {
  771. newNumInt += 1
  772. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  773. }
  774. } else {
  775. newNum = num
  776. }
  777. } else if num > -1 {
  778. // 这是小数
  779. str := strconv.FormatFloat(num, 'f', -1, 64)
  780. // 去除小数点和负号
  781. str = removeDecimalPoint(str)
  782. // 计算字符串长度
  783. lenStr := len(str)
  784. if lenStr > baseLen {
  785. newNumStr := str[0:baseLen]
  786. newNumInt, _ := strconv.Atoi(newNumStr)
  787. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  788. newNum = -newNum
  789. if newNum < num {
  790. newNumInt -= 1
  791. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  792. newNum = -newNum
  793. }
  794. } else {
  795. newNum = num
  796. }
  797. if newNum == -0 {
  798. newNum = 0
  799. }
  800. } else { // 小于等于-1
  801. tmpNumFloat := math.Abs(num)
  802. tmpNum := int(math.Floor(tmpNumFloat)) // 向上取整
  803. str := strconv.Itoa(tmpNum)
  804. lenStr := len(str)
  805. if lenStr > baseLen {
  806. newNumStr := str[0:baseLen]
  807. //fmt.Println("newNumStr:", newNumStr)
  808. newNumInt, _ := strconv.Atoi(newNumStr)
  809. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  810. newNum = -newNum
  811. if newNum < num {
  812. newNumInt -= 1
  813. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  814. newNum = -newNum
  815. }
  816. } else {
  817. newNum = float64(-tmpNum)
  818. }
  819. }
  820. return
  821. }
  822. // GetFloorNewNum 保留n位有效数字的向下取整
  823. // @params num 实际数据
  824. // @params baseLen 需要保留的有效位数
  825. func GetFloorNewNum(num float64, baseLen int) (newNum float64) {
  826. if num >= 1 {
  827. tmpNum := int(math.Floor(num)) // 向上取整
  828. str := strconv.Itoa(tmpNum)
  829. lenStr := len(str)
  830. if lenStr > baseLen {
  831. newNumStr := str[0:baseLen]
  832. newNumInt, _ := strconv.Atoi(newNumStr)
  833. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  834. if newNum < num {
  835. newNumInt -= 1
  836. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  837. }
  838. } else {
  839. newNum = float64(tmpNum)
  840. }
  841. return
  842. } else if num > 0 {
  843. // 这是小数
  844. str := strconv.FormatFloat(num, 'f', -1, 64)
  845. // 去除小数点和负号
  846. str = removeDecimalPoint(str)
  847. // 计算字符串长度
  848. lenStr := len(str)
  849. if lenStr > baseLen {
  850. newNumStr := str[0:baseLen]
  851. newNumInt, _ := strconv.Atoi(newNumStr)
  852. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  853. if newNum > num {
  854. newNumInt -= 1
  855. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  856. }
  857. } else {
  858. newNum = num
  859. }
  860. } else if num > -1 {
  861. // 这是小数
  862. str := strconv.FormatFloat(num, 'f', -1, 64)
  863. // 去除小数点和负号
  864. str = removeDecimalPoint(str)
  865. // 计算字符串长度
  866. lenStr := len(str)
  867. if lenStr > baseLen {
  868. newNumStr := str[0:baseLen]
  869. newNumInt, _ := strconv.Atoi(newNumStr)
  870. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  871. newNum = -newNum
  872. if newNum > num {
  873. newNumInt += 1
  874. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  875. newNum = -newNum
  876. }
  877. } else {
  878. newNum = num
  879. }
  880. if newNum == -0 {
  881. newNum = 0
  882. }
  883. } else { // 小于等于-1
  884. tmpNumFloat := math.Abs(num)
  885. tmpNum := int(math.Ceil(tmpNumFloat)) // 向上取整
  886. str := strconv.Itoa(tmpNum)
  887. lenStr := len(str)
  888. if lenStr > baseLen {
  889. newNumStr := str[0:baseLen]
  890. //fmt.Println("newNumStr:", newNumStr)
  891. newNumInt, _ := strconv.Atoi(newNumStr)
  892. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  893. newNum = -newNum
  894. if newNum > num {
  895. newNumInt += 1
  896. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  897. newNum = -newNum
  898. }
  899. } else {
  900. newNum = float64(-tmpNum)
  901. }
  902. }
  903. return
  904. }
  905. // 去除小数点和负号
  906. func removeDecimalPoint(str string) string {
  907. // 去除小数点
  908. str = str[strings.Index(str, ".")+1:]
  909. return str
  910. }
  911. func GetLocalIP() (ip string, err error) {
  912. addrs, err := net.InterfaceAddrs()
  913. if err != nil {
  914. return
  915. }
  916. for _, addr := range addrs {
  917. ipAddr, ok := addr.(*net.IPNet)
  918. if !ok {
  919. continue
  920. }
  921. if ipAddr.IP.IsLoopback() {
  922. continue
  923. }
  924. if !ipAddr.IP.IsGlobalUnicast() {
  925. continue
  926. }
  927. return ipAddr.IP.String(), nil
  928. }
  929. return
  930. }
  931. func GetDateByDateTypeV2(dateType int, tmpStartDate, tmpEndDate string, startYear int, latestDate time.Time) (startDate, endDate string) {
  932. startDate = tmpStartDate
  933. endDate = tmpEndDate
  934. switch dateType {
  935. case 1:
  936. startDate = "2000-01-01"
  937. endDate = ""
  938. case 2:
  939. startDate = "2010-01-01"
  940. endDate = ""
  941. case 3:
  942. startDate = "2015-01-01"
  943. endDate = ""
  944. case 4:
  945. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  946. startDate = "2021-01-01"
  947. endDate = ""
  948. case 5:
  949. //startDate = startDate + "-01"
  950. //endDate = endDate + "-01"
  951. case 6:
  952. //startDate = startDate + "-01"
  953. endDate = ""
  954. case 7:
  955. startDate = "2018-01-01"
  956. endDate = ""
  957. case 8:
  958. startDate = "2019-01-01"
  959. endDate = ""
  960. case 9:
  961. startDate = "2020-01-01"
  962. endDate = ""
  963. case 11:
  964. startDate = "2022-01-01"
  965. endDate = ""
  966. case 12:
  967. startDate = "2023-01-01"
  968. endDate = ""
  969. case 13:
  970. startDate = "2024-01-01"
  971. endDate = ""
  972. case DateTypeNYears:
  973. if startYear == 0 { //默认取最近5年
  974. startYear = 5
  975. }
  976. if latestDate.IsZero() {
  977. return
  978. }
  979. startDate = latestDate.AddDate(-startYear, 0, 0).Format(FormatDate)
  980. endDate = ""
  981. }
  982. // 兼容日期错误
  983. {
  984. if strings.Count(startDate, "-") == 1 {
  985. startDate = startDate + "-01"
  986. }
  987. if strings.Count(endDate, "-") == 1 {
  988. endTime, err := time.Parse(FormatYearMonthDate, endDate)
  989. if err != nil {
  990. return
  991. }
  992. endDate = endTime.AddDate(0, 1, -1).Format(FormatDate)
  993. }
  994. }
  995. return
  996. }
  997. func GetColorMap() map[int]string {
  998. colorMap := make(map[int]string)
  999. colors := []string{"#0000FF", "#FF0000", "#999999", "#000000", "#7CB5EC", "#90ED7D", "#F7A35C", "#8085E9",
  1000. "#F15C80", "#E4D354", "#2B908F", "#F45B5B", "#91E8E1", "#FDA8C7", "#8A4294",
  1001. "#578B5A", "#0033FF", "#849EC1", "#FFDF0C", "#005496", "#00F0FF", "#4D535B",
  1002. "#4F4C34", "#804141", "#86BABD", "#8AA3FF", "#960000", "#A173DB", "#A39340",
  1003. "#CE814A", "#D1D2E6", "#EAB7B7", "#FF2E7A", "#FF4AF8", "#FF785B", "#FF9696", "#FFA800", "#FFBC97", "#FFDFDF"}
  1004. for k, v := range colors {
  1005. colorMap[k] = v
  1006. }
  1007. return colorMap
  1008. }
  1009. // GetDaysDiff1900 计算日期距离1900-01-01的天数
  1010. func GetDaysDiff1900(date string) int {
  1011. // 将字符串转换为时间类型
  1012. //从1899年12月30日开始是因为Excel的日期计算是基于1900年1月1日的,而1900年并不是闰年,因此Excel日期计算存在一个错误。为了修正这个错误,
  1013. //我们将时间回溯到1899年12月30日,这样在进行日期计算时可以正确地处理Excel日期。
  1014. tStart, err := time.ParseInLocation(FormatDate, "1899-12-30", time.Local)
  1015. if err != nil {
  1016. return 0
  1017. }
  1018. tEnd, err := time.ParseInLocation(FormatDate, date, time.Local)
  1019. if err != nil {
  1020. return 0
  1021. }
  1022. // 计算两个日期之间的天数差值
  1023. duration := tEnd.Sub(tStart).Hours() / 24
  1024. days := int(duration)
  1025. return days
  1026. }
  1027. func ReplaceFormulaByTagMap(valTagMap map[string]int, formulaStr string) string {
  1028. funMap := getFormulaMap()
  1029. for k, v := range funMap {
  1030. formulaStr = strings.Replace(formulaStr, k, v, -1)
  1031. }
  1032. replaceCount := 0
  1033. for tag, val := range valTagMap {
  1034. dvStr := fmt.Sprintf("%v", val)
  1035. formulaStr = strings.Replace(formulaStr, tag, dvStr, -1)
  1036. replaceCount++
  1037. }
  1038. for k, v := range funMap {
  1039. formulaStr = strings.Replace(formulaStr, v, k, -1)
  1040. }
  1041. return formulaStr
  1042. }
  1043. // GetFrequencyEn 获取频度的英文版
  1044. func GetFrequencyEn(frequency string) (frequencyEn string) {
  1045. switch frequency {
  1046. case "日度":
  1047. frequencyEn = "day"
  1048. return
  1049. case "周度":
  1050. frequencyEn = "week"
  1051. return
  1052. case "旬度":
  1053. frequencyEn = "ten days"
  1054. return
  1055. case "月度":
  1056. frequencyEn = "month"
  1057. return
  1058. case "季度":
  1059. frequencyEn = "quarter"
  1060. return
  1061. case "年度":
  1062. frequencyEn = "year"
  1063. return
  1064. }
  1065. return
  1066. }
  1067. // DateConvMysqlConvMongo
  1068. // @Description: 将mysql中的日期比较符转换成mongo中的日期比较符
  1069. // @author: Roc
  1070. // @datetime 2024-05-08 11:03:26
  1071. // @param dateCon string
  1072. func DateConvMysqlConvMongo(dateCon string) string {
  1073. cond := ""
  1074. switch dateCon {
  1075. case "=":
  1076. cond = "$eq"
  1077. case "<":
  1078. cond = "$lt"
  1079. case "<=":
  1080. cond = "$lte"
  1081. case ">":
  1082. cond = "$gt"
  1083. case ">=":
  1084. cond = "$gte"
  1085. }
  1086. return cond
  1087. }
  1088. // HmacSha256 计算HmacSha256
  1089. // key 是加密所使用的key
  1090. // data 是加密的内容
  1091. func HmacSha256(key string, data string) []byte {
  1092. mac := hmac.New(sha256.New, []byte(key))
  1093. _, _ = mac.Write([]byte(data))
  1094. return mac.Sum(nil)
  1095. }
  1096. // HmacSha256ToBase64 将加密后的二进制转Base64字符串
  1097. func HmacSha256ToBase64(key string, data string) string {
  1098. return base64.URLEncoding.EncodeToString(HmacSha256(key, data))
  1099. }
  1100. func GetSign(nonce, timestamp, appId, secret string) (sign string) {
  1101. signStrMap := map[string]string{
  1102. "nonce": nonce,
  1103. "timestamp": timestamp,
  1104. "appid": appId,
  1105. }
  1106. keys := make([]string, 0, len(signStrMap))
  1107. for k := range signStrMap {
  1108. keys = append(keys, k)
  1109. }
  1110. sort.Strings(keys)
  1111. var signStr string
  1112. for _, k := range keys {
  1113. signStr += k + "=" + signStrMap[k] + "&"
  1114. }
  1115. signStr = strings.Trim(signStr, "&")
  1116. fmt.Println("signStr:" + signStr)
  1117. sign = HmacSha256ToBase64(secret, signStr)
  1118. return
  1119. }
  1120. func TimeTransferString(format string, t time.Time) string {
  1121. str := t.Format(format)
  1122. if t.IsZero() {
  1123. return ""
  1124. }
  1125. return str
  1126. }
  1127. func DesBase64Decrypt(crypted []byte, desKey string) []byte {
  1128. result, _ := base64.StdEncoding.DecodeString(string(crypted))
  1129. remain := len(result) % 8
  1130. if remain > 0 {
  1131. mod := 8 - remain
  1132. for i := 0; i < mod; i++ {
  1133. result = append(result, 0)
  1134. }
  1135. }
  1136. origData, err := TripleDesDecrypt(result, []byte(desKey))
  1137. if err != nil {
  1138. panic(any(err))
  1139. }
  1140. return origData
  1141. }
  1142. // // 3DES解密
  1143. func TripleDesDecrypt(crypted, key []byte) ([]byte, error) {
  1144. block, err := des.NewTripleDESCipher(key)
  1145. if err != nil {
  1146. return nil, err
  1147. }
  1148. blockMode := cipher.NewCBCDecrypter(block, key[:8])
  1149. origData := make([]byte, len(crypted))
  1150. // origData := crypted
  1151. blockMode.CryptBlocks(origData, crypted)
  1152. origData = PKCS5UnPadding(origData)
  1153. // origData = ZeroUnPadding(origData)
  1154. return origData, nil
  1155. }
  1156. func PKCS5UnPadding(origData []byte) []byte {
  1157. length := len(origData)
  1158. // 去掉最后一个字节 unpadding 次
  1159. unpadding := int(origData[length-1])
  1160. return origData[:(length - unpadding)]
  1161. }
  1162. // handleSystemAppointDateT
  1163. // @Description: 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  1164. // @author: Roc
  1165. // @datetime2023-10-27 09:31:35
  1166. // @param Frequency string
  1167. // @param Day string
  1168. // @return date string
  1169. // @return err error
  1170. // @return errMsg string
  1171. func HandleSystemAppointDateT(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
  1172. //currDate := time.Now()
  1173. switch frequency {
  1174. case "本周":
  1175. day := int(currDate.Weekday())
  1176. if day == 0 { // 周日
  1177. day = 7
  1178. }
  1179. num := 0
  1180. switch appointDay {
  1181. case "周一":
  1182. num = 1
  1183. case "周二":
  1184. num = 2
  1185. case "周三":
  1186. num = 3
  1187. case "周四":
  1188. num = 4
  1189. case "周五":
  1190. num = 5
  1191. case "周六":
  1192. num = 6
  1193. case "周日":
  1194. num = 7
  1195. }
  1196. day = num - day
  1197. date = currDate.AddDate(0, 0, day).Format(FormatDate)
  1198. case "本旬":
  1199. day := currDate.Day()
  1200. var tmpDate time.Time
  1201. switch appointDay {
  1202. case "第一天":
  1203. if day <= 10 {
  1204. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1205. } else if day <= 20 {
  1206. tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
  1207. } else {
  1208. tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
  1209. }
  1210. case "最后一天":
  1211. if day <= 10 {
  1212. tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
  1213. } else if day <= 20 {
  1214. tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
  1215. } else {
  1216. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1217. }
  1218. }
  1219. date = tmpDate.Format(FormatDate)
  1220. case "本月":
  1221. var tmpDate time.Time
  1222. switch appointDay {
  1223. case "第一天":
  1224. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1225. case "最后一天":
  1226. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1227. }
  1228. date = tmpDate.Format(FormatDate)
  1229. case "本季":
  1230. month := currDate.Month()
  1231. var tmpDate time.Time
  1232. switch appointDay {
  1233. case "第一天":
  1234. if month <= 3 {
  1235. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1236. } else if month <= 6 {
  1237. tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
  1238. } else if month <= 9 {
  1239. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1240. } else {
  1241. tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
  1242. }
  1243. case "最后一天":
  1244. if month <= 3 {
  1245. tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
  1246. } else if month <= 6 {
  1247. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1248. } else if month <= 9 {
  1249. tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
  1250. } else {
  1251. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1252. }
  1253. }
  1254. date = tmpDate.Format(FormatDate)
  1255. case "本半年":
  1256. month := currDate.Month()
  1257. var tmpDate time.Time
  1258. switch appointDay {
  1259. case "第一天":
  1260. if month <= 6 {
  1261. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1262. } else {
  1263. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1264. }
  1265. case "最后一天":
  1266. if month <= 6 {
  1267. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1268. } else {
  1269. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1270. }
  1271. }
  1272. date = tmpDate.Format(FormatDate)
  1273. case "本年":
  1274. var tmpDate time.Time
  1275. switch appointDay {
  1276. case "第一天":
  1277. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1278. case "最后一天":
  1279. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1280. }
  1281. date = tmpDate.Format(FormatDate)
  1282. default:
  1283. errMsg = "错误的日期频度:" + frequency
  1284. err = errors.New(errMsg)
  1285. return
  1286. }
  1287. return
  1288. }
  1289. func CompareFloatByOpStrings(op string, a, b float64) bool {
  1290. switch op {
  1291. case "=":
  1292. return a == b
  1293. case ">":
  1294. return a > b
  1295. case ">=":
  1296. return a >= b
  1297. case "<=":
  1298. return a <= b
  1299. case "<":
  1300. return a < b
  1301. }
  1302. return false
  1303. }
  1304. // RoundNumber 保留小数位数
  1305. func RoundNumber(num string, decimalPlaces int, hasPercent bool) string {
  1306. numDecimal, _ := decimal.NewFromString(num)
  1307. if hasPercent {
  1308. numDecimal = numDecimal.Mul(decimal.NewFromInt(100))
  1309. }
  1310. numStr := numDecimal.Round(int32(decimalPlaces)).StringFixed(int32(decimalPlaces))
  1311. if hasPercent {
  1312. numStr += "%"
  1313. }
  1314. return numStr
  1315. }
  1316. // ForwardPars
  1317. // @Description: 向前插入参数
  1318. // @param pars
  1319. // @param values
  1320. // @return []interface{}
  1321. func ForwardPars(pars []interface{}, values ...interface{}) []interface{} {
  1322. if len(values) <= 0 {
  1323. return pars
  1324. }
  1325. return append(values, pars...)
  1326. }
  1327. // GormDateStrToDateTimeStr
  1328. // @Description: gorm日期字符串格式转正常显示的日期时间字符串
  1329. // @param originalString
  1330. // @return formatStr
  1331. func GormDateStrToDateTimeStr(originalString string) (formatStr string) {
  1332. if originalString == `` {
  1333. return
  1334. }
  1335. if strings.Contains(originalString, "0001-01-01") {
  1336. return
  1337. }
  1338. formatStr = originalString
  1339. if !strings.Contains(originalString, "T") {
  1340. return
  1341. }
  1342. // 解析原始字符串
  1343. t, err := time.Parse(FormatDateWallWithLoc, originalString)
  1344. if err != nil {
  1345. fmt.Println("Error parsing time:", err)
  1346. return
  1347. }
  1348. // 重新格式化时间
  1349. formatStr = t.Format(FormatDateTime)
  1350. return
  1351. }
  1352. // GormDateStrToDateStr
  1353. // @Description: gorm日期字符串格式转正常显示的日期字符串
  1354. // @param originalString
  1355. // @return formatStr
  1356. func GormDateStrToDateStr(originalString string) (formatStr string) {
  1357. if originalString == `` {
  1358. return
  1359. }
  1360. if strings.Contains(originalString, "0001-01-01") {
  1361. return
  1362. }
  1363. formatStr = originalString
  1364. if !strings.Contains(originalString, "T") {
  1365. return
  1366. }
  1367. // 解析原始字符串
  1368. t, err := time.Parse(FormatDateWallWithLoc, originalString)
  1369. if err != nil {
  1370. fmt.Println("Error parsing time:", err)
  1371. return
  1372. }
  1373. // 重新格式化时间
  1374. formatStr = t.Format(FormatDate)
  1375. return
  1376. }