common.go 37 KB

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