common.go 29 KB

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