common.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  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. endDate = endDate + "-01"
  945. }
  946. }
  947. return
  948. }
  949. func GetColorMap() map[int]string {
  950. colorMap := make(map[int]string)
  951. colors := []string{"#0000FF", "#FF0000", "#999999", "#000000", "#7CB5EC", "#90ED7D", "#F7A35C", "#8085E9",
  952. "#F15C80", "#E4D354", "#2B908F", "#F45B5B", "#91E8E1", "#FDA8C7", "#8A4294",
  953. "#578B5A", "#0033FF", "#849EC1", "#FFDF0C", "#005496", "#00F0FF", "#4D535B",
  954. "#4F4C34", "#804141", "#86BABD", "#8AA3FF", "#960000", "#A173DB", "#A39340",
  955. "#CE814A", "#D1D2E6", "#EAB7B7", "#FF2E7A", "#FF4AF8", "#FF785B", "#FF9696", "#FFA800", "#FFBC97", "#FFDFDF"}
  956. for k, v := range colors {
  957. colorMap[k] = v
  958. }
  959. return colorMap
  960. }
  961. // GetDaysDiff1900 计算日期距离1900-01-01的天数
  962. func GetDaysDiff1900(date string) int {
  963. // 将字符串转换为时间类型
  964. //从1899年12月30日开始是因为Excel的日期计算是基于1900年1月1日的,而1900年并不是闰年,因此Excel日期计算存在一个错误。为了修正这个错误,
  965. //我们将时间回溯到1899年12月30日,这样在进行日期计算时可以正确地处理Excel日期。
  966. tStart, err := time.ParseInLocation(FormatDate, "1899-12-30", time.Local)
  967. if err != nil {
  968. return 0
  969. }
  970. tEnd, err := time.ParseInLocation(FormatDate, date, time.Local)
  971. if err != nil {
  972. return 0
  973. }
  974. // 计算两个日期之间的天数差值
  975. duration := tEnd.Sub(tStart).Hours() / 24
  976. days := int(duration)
  977. return days
  978. }
  979. func ReplaceFormulaByTagMap(valTagMap map[string]int, formulaStr string) string {
  980. funMap := getFormulaMap()
  981. for k, v := range funMap {
  982. formulaStr = strings.Replace(formulaStr, k, v, -1)
  983. }
  984. replaceCount := 0
  985. for tag, val := range valTagMap {
  986. dvStr := fmt.Sprintf("%v", val)
  987. formulaStr = strings.Replace(formulaStr, tag, dvStr, -1)
  988. replaceCount++
  989. }
  990. for k, v := range funMap {
  991. formulaStr = strings.Replace(formulaStr, v, k, -1)
  992. }
  993. return formulaStr
  994. }
  995. // GetFrequencyEn 获取频度的英文版
  996. func GetFrequencyEn(frequency string) (frequencyEn string) {
  997. switch frequency {
  998. case "日度":
  999. frequencyEn = "day"
  1000. return
  1001. case "周度":
  1002. frequencyEn = "week"
  1003. return
  1004. case "旬度":
  1005. frequencyEn = "ten days"
  1006. return
  1007. case "月度":
  1008. frequencyEn = "month"
  1009. return
  1010. case "季度":
  1011. frequencyEn = "quarter"
  1012. return
  1013. case "年度":
  1014. frequencyEn = "year"
  1015. return
  1016. }
  1017. return
  1018. }
  1019. // DateConvMysqlConvMongo
  1020. // @Description: 将mysql中的日期比较符转换成mongo中的日期比较符
  1021. // @author: Roc
  1022. // @datetime 2024-05-08 11:03:26
  1023. // @param dateCon string
  1024. func DateConvMysqlConvMongo(dateCon string) string {
  1025. cond := ""
  1026. switch dateCon {
  1027. case "=":
  1028. cond = "$eq"
  1029. case "<":
  1030. cond = "$lt"
  1031. case "<=":
  1032. cond = "$lte"
  1033. case ">":
  1034. cond = "$gt"
  1035. case ">=":
  1036. cond = "$gte"
  1037. }
  1038. return cond
  1039. }
  1040. func DesBase64Decrypt(crypted []byte, desKey string) []byte {
  1041. result, _ := base64.StdEncoding.DecodeString(string(crypted))
  1042. remain := len(result) % 8
  1043. if remain > 0 {
  1044. mod := 8 - remain
  1045. for i := 0; i < mod; i++ {
  1046. result = append(result, 0)
  1047. }
  1048. }
  1049. origData, err := TripleDesDecrypt(result, []byte(desKey))
  1050. if err != nil {
  1051. panic(any(err))
  1052. }
  1053. return origData
  1054. }
  1055. // // 3DES解密
  1056. func TripleDesDecrypt(crypted, key []byte) ([]byte, error) {
  1057. block, err := des.NewTripleDESCipher(key)
  1058. if err != nil {
  1059. return nil, err
  1060. }
  1061. blockMode := cipher.NewCBCDecrypter(block, key[:8])
  1062. origData := make([]byte, len(crypted))
  1063. // origData := crypted
  1064. blockMode.CryptBlocks(origData, crypted)
  1065. origData = PKCS5UnPadding(origData)
  1066. // origData = ZeroUnPadding(origData)
  1067. return origData, nil
  1068. }
  1069. func PKCS5UnPadding(origData []byte) []byte {
  1070. length := len(origData)
  1071. // 去掉最后一个字节 unpadding 次
  1072. unpadding := int(origData[length-1])
  1073. return origData[:(length - unpadding)]
  1074. }
  1075. func TimeTransferString(format string, t time.Time) string {
  1076. str := t.Format(format)
  1077. if t.IsZero() {
  1078. return ""
  1079. }
  1080. return str
  1081. }
  1082. // handleSystemAppointDateT
  1083. // @Description: 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  1084. // @author: Roc
  1085. // @datetime2023-10-27 09:31:35
  1086. // @param Frequency string
  1087. // @param Day string
  1088. // @return date string
  1089. // @return err error
  1090. // @return errMsg string
  1091. func HandleSystemAppointDateT(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
  1092. //currDate := time.Now()
  1093. switch frequency {
  1094. case "本周":
  1095. day := int(currDate.Weekday())
  1096. if day == 0 { // 周日
  1097. day = 7
  1098. }
  1099. num := 0
  1100. switch appointDay {
  1101. case "周一":
  1102. num = 1
  1103. case "周二":
  1104. num = 2
  1105. case "周三":
  1106. num = 3
  1107. case "周四":
  1108. num = 4
  1109. case "周五":
  1110. num = 5
  1111. case "周六":
  1112. num = 6
  1113. case "周日":
  1114. num = 7
  1115. }
  1116. day = num - day
  1117. date = currDate.AddDate(0, 0, day).Format(FormatDate)
  1118. case "本旬":
  1119. day := currDate.Day()
  1120. var tmpDate time.Time
  1121. switch appointDay {
  1122. case "第一天":
  1123. if day <= 10 {
  1124. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1125. } else if day <= 20 {
  1126. tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
  1127. } else {
  1128. tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
  1129. }
  1130. case "最后一天":
  1131. if day <= 10 {
  1132. tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
  1133. } else if day <= 20 {
  1134. tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
  1135. } else {
  1136. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1137. }
  1138. }
  1139. date = tmpDate.Format(FormatDate)
  1140. case "本月":
  1141. var tmpDate time.Time
  1142. switch appointDay {
  1143. case "第一天":
  1144. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1145. case "最后一天":
  1146. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1147. }
  1148. date = tmpDate.Format(FormatDate)
  1149. case "本季":
  1150. month := currDate.Month()
  1151. var tmpDate time.Time
  1152. switch appointDay {
  1153. case "第一天":
  1154. if month <= 3 {
  1155. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1156. } else if month <= 6 {
  1157. tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
  1158. } else if month <= 9 {
  1159. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1160. } else {
  1161. tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
  1162. }
  1163. case "最后一天":
  1164. if month <= 3 {
  1165. tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
  1166. } else if month <= 6 {
  1167. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1168. } else if month <= 9 {
  1169. tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
  1170. } else {
  1171. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1172. }
  1173. }
  1174. date = tmpDate.Format(FormatDate)
  1175. case "本半年":
  1176. month := currDate.Month()
  1177. var tmpDate time.Time
  1178. switch appointDay {
  1179. case "第一天":
  1180. if month <= 6 {
  1181. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1182. } else {
  1183. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1184. }
  1185. case "最后一天":
  1186. if month <= 6 {
  1187. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1188. } else {
  1189. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1190. }
  1191. }
  1192. date = tmpDate.Format(FormatDate)
  1193. case "本年":
  1194. var tmpDate time.Time
  1195. switch appointDay {
  1196. case "第一天":
  1197. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1198. case "最后一天":
  1199. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1200. }
  1201. date = tmpDate.Format(FormatDate)
  1202. default:
  1203. errMsg = "错误的日期频度:" + frequency
  1204. err = errors.New(errMsg)
  1205. return
  1206. }
  1207. return
  1208. }
  1209. func CompareFloatByOpStrings(op string, a, b float64) bool {
  1210. switch op {
  1211. case "=":
  1212. return a == b
  1213. case ">":
  1214. return a > b
  1215. case ">=":
  1216. return a >= b
  1217. case "<=":
  1218. return a <= b
  1219. case "<":
  1220. return a < b
  1221. }
  1222. return false
  1223. }
  1224. // GormDateStrToDateTimeStr
  1225. // @Description: gorm日期字符串格式转正常显示的日期时间字符串
  1226. // @param originalString
  1227. // @return formatStr
  1228. func GormDateStrToDateTimeStr(originalString string) (formatStr string) {
  1229. formatStr = originalString
  1230. if !strings.Contains(originalString, "T") {
  1231. return
  1232. }
  1233. // 解析原始字符串
  1234. t, err := time.Parse(FormatDateWallWithLoc, originalString)
  1235. if err != nil {
  1236. fmt.Println("Error parsing time:", err)
  1237. return
  1238. }
  1239. // 重新格式化时间
  1240. formatStr = t.Format(FormatDateTime)
  1241. return
  1242. }
  1243. // GormDateStrToDateStr
  1244. // @Description: gorm日期字符串格式转正常显示的日期字符串
  1245. // @param originalString
  1246. // @return formatStr
  1247. func GormDateStrToDateStr(originalString string) (formatStr string) {
  1248. formatStr = originalString
  1249. if !strings.Contains(originalString, "T") {
  1250. return
  1251. }
  1252. // 解析原始字符串
  1253. t, err := time.Parse(FormatDateWallWithLoc, originalString)
  1254. if err != nil {
  1255. fmt.Println("Error parsing time:", err)
  1256. return
  1257. }
  1258. // 重新格式化时间
  1259. formatStr = t.Format(FormatDate)
  1260. return
  1261. }
  1262. // RoundNumber 保留小数位数
  1263. func RoundNumber(num string, decimalPlaces int, hasPercent bool) string {
  1264. numDecimal, _ := decimal.NewFromString(num)
  1265. if hasPercent {
  1266. numDecimal = numDecimal.Mul(decimal.NewFromInt(100))
  1267. }
  1268. numFloat, _ := numDecimal.Round(int32(decimalPlaces)).Float64()
  1269. numStr := strconv.FormatFloat(numFloat, 'f', decimalPlaces, 64)
  1270. if hasPercent {
  1271. numStr += "%"
  1272. }
  1273. return numStr
  1274. }