common.go 36 KB

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