common.go 25 KB

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