common.go 36 KB

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