common.go 25 KB

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