common.go 34 KB

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