common.go 27 KB

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