common.go 23 KB

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