common.go 27 KB

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