common.go 29 KB

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