common.go 24 KB

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