common.go 35 KB

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